redux-act
An opinionated lib to create actions and reducers for Redux. The main goal is to use actions themselves as references inside the reducers rather than string constants.
Install
# NPM npm install redux-act --save# Yarn yarn add redux-act
You can also use a browser friendly compiled file or the minified version from NPM CDN (mostly for online demo / snippets).
Browser support: this lib uses String.prototype.startsWith
which is not supported by IE11. Be sure to add a polyfill if you are targeting this browser. Learn more.
Content
Usage
Even if there is a function named createAction
, it actually creates an action creator
according to Redux glossary. It was just a bit overkill to name the function createActionCreator
. If you are not sure if something is an action or an action creator, just remember that actions are plain objects while action creators are functions.
// Import functions;; // Create an action creator (description is optional)const add = ;const increment = ;const decrement = ; // Create a reducer// (ES6 syntax, see Advanced usage below for an alternative for ES5)const counterReducer = ; // <-- This is the default state // Create the storeconst counterStore = ; // Dispatch actionscounterStore; // counterStore.getState() === 1counterStore; // counterStore.getState() === 2counterStore; // counterStore.getState() === 1counterStore; // counterStore.getState() === 6
FAQ
-
Does it work with Redux devtools? Yes.
-
Do reducers work with combineReducers? Of course, they are just normal reducers after all. Remember that according to the
combineReducers
checks, you will need to provide a default state when creating each reducer before combining them. -
How does it work? There is not much magic. A generated id is prepended to each action type and will be used inside reducers instead of the string constants used inside Redux by default.
-
Can you show how different it is from writing classic Redux? Sure, you can check both commits to update counter example and todomvc example. You can also run both examples with
npm install && npm start
inside each folder. -
Why having two syntax to create reducers? The one with only a map of
action => reduce function
doesn't allow much. This is why the other one is here, in case you would need a small state inside the reducer, having something similar as an actor, or whatever you feel like. Also, one of the syntax is ES6 only. -
Inside a reducer, why is it
(state, payload) => newState
rather than(state, action) => newState
? You can find more info about that on thecreateReducer
API below, but basically, that's because an action is composed of metadata handled by the lib and your payload. Since you only care about that part, better to have it directly. You can switch back to the full action if necessary of course. -
Why have you done that? Aren't string constants good enough? I know that the Redux doc states that such magic isn't really good, that saving a few lines of code isn't worth hiding such logic. I can understand that. And don't get me wrong, the main goal of this lib isn't to reduce boilerplate (even if I like that it does) but to use the actions themselves as keys for the reducers rather than strings which are error prone. You never know what the new dev on your project might do... Maybe (s)he will not realize that the new constant (s)he just introduced was already existing and now everything is broken and a wormhole will appear and it will be the end of mankind. Let's prevent that!
Advanced usage
;; // You can create several action creators at once// (but that's probably not the best way to do it)const increment decrement = 'inc' 'dec'; // When creating action creators, the description is optional// it will only be used for devtools and logging stuff.// It's better to put something but feel free to leave it empty if you want to.const replace = ; // By default, the payload of the action is the first argument// when you call the action. If you need to support several arguments,// you can specify a function on how to merge all arguments into// an unique payload.let append = ; // There is another pattern to create reducers// and it works fine with ES5! (maybe even ES3 \o/)const stringReducer = ; // <-- Default state // Rather than binding the action creators each time you want to use them,// you can do it once and for all as soon as you have the targeted store// assignTo: mutates the action creator itself// bindTo: returns a new action creator assigned to the storeconst stringStore = ;replace;append = append; // Now, when calling actions, they will be automatically dispatched; // stringStore.getState() === 'missing a letter'; // stringStore.getState() === 'a'; // stringStore.getState() === 'abcd' // If you really need serializable actions, using string constant rather// than runtime generated id, just use a uppercase description (with eventually some underscores)// and it will be use as the id of the actionconst doSomething = ;; // { type: 'STRING_CONSTANT', payload: 1} // Little bonus, if you need to support metadata around your action,// like needed data but not really part of the payload, you add a second functionconst metaAction = ; // Metadata will be the third argument of the reduce function;
API
createAction([description], [payloadReducer], [metaReducer])
Parameters
- description (string, optional): used by logging and devtools when displaying the action. If this parameter is uppercase only, with underscores and numbers, it will be used as the action type without any generated id. You can use this feature to have serializable actions you can share between client and server.
- payloadReducer (function, optional): transform multiple arguments as a unique payload.
- metaReducer (function, optional): transform multiple arguments as a unique metadata object.
Usage
Returns a new action creator. If you specify a description, it will be used by devtools. By default, createAction
will return a function and its first argument will be used as the payload when dispatching the action. If you need to support multiple arguments, you need to specify a payload reducer in order to merge all arguments into one unique payload.
// Super simple actionconst simpleAction = ;// Better to add a descriptionconst betterAction = ;// Support multiple arguments by merging themconst multipleAction = // Again, better to add a descriptionconst bestAction = // Serializable action (the description will be used as the unique identifier)const serializableAction = ;
action creator
An action creator is basically a function that takes arguments and return an action which has the following format:
type
: generated id + your description.payload
: the data passed when calling the action creator. Will be the first argument of the function except if you specified a payload reducer when creating the action.meta
: if you have provided a metaReducer, it will be used to create a metadata object assigned to this key. Otherwise, it'sundefined
.error
: a boolean indicating if the action is an error according to FSA.
const addTodo = ;;// return { type: '[1] Add todo', payload: 'content' } const editTodo = ;;// return { type: '[2] Edit todo', payload: {id: 42, content: 'the answer'} } const serializeTodo = ;;// return { type: 'SERIALIZE_TODO', payload: 1 }
An action creator has the following methods:
getType()
Return the generated type that will be used by all actions from this action creator. Useful for compatibility purposes.
assignTo(store | dispatch)
Remember that you still need to dispatch those actions. If you already have one or more stores, you can assign the action using the assignTo
function. This will mutate the action creator itself. You can pass one store or one dispatch function or an array of any of both.
let action = ;let action2 = ;const reducer = ;const store = ;const store2 = ; // Automatically dispatch the action to the store when calledaction;; // store.getState() === 2; // store.getState() === 4; // store.getState() === 8 // You can assign the action to several stores using an arrayaction;;// store.getState() === 16// store2.getState() === -2
bindTo(store | dispatch)
If you need immutability, you can use bindTo
, it will return a new action creator which will automatically dispatch its action.
// If you need more immutability, you can bind them, creating a new action creatorconst boundAction = action2;; // Not doing anything since not assigned nor bound// store.getState() === 16// store2.getState() === -2; // store.getState() === 8
assigned() / bound() / dispatched()
Test the current status of the action creator.
const action = ;action; // false, not assignedaction; // false, not boundaction; // false, test if either assigned or bound const boundAction = action;boundAction; // falseboundAction; // trueboundAction; // true action;action; // trueaction; // falseaction; // true
raw(...args)
When an action creator is either assigned or bound, it will no longer only return the action object but also dispatch it. In some cases, you will need the action without dispatching it (when batching actions for example). In order to achieve that, you can use the raw
method which will return the bare action. You could say that it is exactly the same as the action creator would behave it if wasn't assigned nor bound.
const action = ;; // store has been updatedaction; // return the action, store hasn't been updated
asError(...args)*
By default, if your payload is an instance of Error
, the action will be tagged as an error. But if you need to use any other kind of payload as an error payload, you can always use this method. It will apply the same payload reducer by setting the error
to true
.
const actionCreator = const goodAction = goodActionerror // false const badAction = badActionerror // true const forcedBadAction = actionCreatorforcedBadActionerror // true
createReducer(handlers, [defaultState])
Parameters
- handlers (object or function): if
object
, a map of action to the reduce function. Iffunction
, take two attributes: a function to register actions and another one to unregister them. See below. - defaultState (anything, optional): the initial state of the reducer. Must not be empty if you plan to use this reducer inside a
combineReducers
.
Usage
Returns a new reducer. It's kind of the same syntax as the Array.prototype.reduce
function. You can specify how to reduce as the first argument and the accumulator, or default state, as the second one. The default state is optional since you can retrieve it from the store when creating it but you should consider always having a default state inside a reducer, especially if you want to use it with combineReducers
which make such default state mandatory.
There are two patterns to create a reducer. One is passing an object as a map of action creators
to reduce functions
. Such functions have the following signature: (previousState, payload) => newState
. The other one is using a function factory. Rather than trying to explaining it, just read the following examples.
const increment = ;const add = ; // First patternconst reducerMap = ; // Second patternconst reducerFactory = ;
reducer
Like everything, a reducer is just a function. It takes the current state and an action payload and return the new state. It has the following methods.
options({ payload: boolean, fallback: [handler] })
Since an action is an object with a type
, a payload
(which is your actual data) and eventually some metadata
, all reduce functions directly take the payload as their 2nd argument and the metadata as the 3rd by default rather than the whole action since all other properties are handled by the lib and you shouldn't care about them anyway. If you really need to use the full action, you can change the behavior of a reducer. Returns the reducer itself for chaining.
const add = ;const sub = ;const reducer = ; reduceroptions payload: false;
You can read a more detailed explanation here.
If you specify a fallback
handler, which has the exact same signature as any action handler inside the reducer, it will be called anytime you dispatch an action which is not handled by the reducer.
const action = ;const reducer = ;reduceroptions // action is not handled, so fallback will be called state + payload;const store = ;store; // 0store;store; // 5store;store; // -5
has(action creator)
Test if the reducer has a reduce function for a particular action creator or a string type.
const add = ;const sub = ;const reducer = ; reducer; // truereducer; // falsereducer; // true
on(action creator | action creator[], reduce function) off(action creator | action creator[])
You can dynamically add and remove actions. See the adding and removing actions section for more infos. You can use either a redux-act
action creator or a raw string type. You can also use array of those, it will apply the on
or off
function to all elements.
They both return the reducer itself so you can chain them.
assignAll(actionCreators, stores)
Parameters
- actionCreators (object or array): which action creators to assign. If it's an object, it's a map of name -> action creator, useful when importing several actions at once.
- stores (object or array): the target store(s) when dispatching actions. Can be only one or several inside an array.
Usage
A common pattern is to export a set of action creators as an object. If you want to bind all of them to a store, there is this super small helper. You can also use an array of action creators. And since you can bind to one or several stores, you can specify either one store or an array of stores.
// actions.jsconst add = ;const sub = ; // reducer.js; actionsadd: state + payload actionssub: state - payload 0; // store.js;; const store = ;; ;
bindAll(actionCreators, stores)
Parameters
- actionCreators (object or array): which action creators to bind. If it's an object, it's a map of name -> action creator, useful when importing several actions at once.
- stores (object or array): the target store(s) when dispatching actions. Can be only one or several inside an array.
Usage
Just like assignAll
, you can bind several action creators at once.
;;; ;
batch(actions)
Parameters
- actions (objects | array): wrap an array of actions inside another action and will reduce them all at once when dispatching it. You can also call this function with several actions as arguments.
⚠️ Warning Does not work with assigned and bound actions by default since those will be dispatched immediately when called. You will need to use the raw
method for such actions. See usage below.
Usage
Useful when you need to run a sequence of actions without impacting your whole application after each one but rather after all of them are done. For example, if you are using @connect
from react-redux
, it is called after each action by default. Using batch
, it will be called only when all actions in the array have been reduced.
batch
is an action creator like any other created using createAction
. You can assign or bind it if you want, especially if you only have one store. You can even use it inside reducers. It is enabled by default, but you can remove it and put it back.
; // Basic actionsconst inc = ;const dec = ; const reducer = ; const store = ;// actions as argumentsstore;// actions as an arraystore;store; // 4 // Assigned actionsinc;dec; // You still need to dispatch the batch action// You will need to use the 'raw' function on the action creators to prevent// the auto-dipatch from the assigned action creatorsstore;store;store; // 2 // Let's de-assign our actionsinc;dec; // You can bind batchconst boundBatch = batch;;store; // 4 // You can assign batchbatch;;store; // 1 // You can remove batch from a reducerreducer;;store; // 1 // You can put it backreducer;;store; // -1
disbatch(store | dispatch, [actions])
Parameters
- store | dispatch (object, which is a Redux store, or a dispatch function): add a
disbatch
function to the store if it is the only parameter. Just likedispatch
but for several actions which will be batched as a single one. - actions (array, optional): the array of actions to dispatch as a batch of actions.
Usage
// All samples will display both syntax with and without an array// They are exactly the same;; // Add 'disbatch' directly to the store;store;store; // Disbatch immediately from store;; // Disbatch immediately from dispatch;;
asError(action)
Parameters
- action (object): a standard Redux action (with a
type
property)
Set the error
property to true
.
; const goodAction = ;goodActionerror; // false const badAction = ;badActionerror; // true
types
This is mostly internal stuff and is exposed only to help during development and testing.
As you know it, each action has a type. redux-act
will ensure that each action creator type is unique. If you are not using serializable actions, you are good to go as all types will be dynamically generated and unique. But if you do use them, by default, nothing prevent you from creating two action creators with the same type. redux-act
will throw if you call createAction
with an already used type, and that is good, except when running tests.
During testing, you might need to reset all types, start as fresh, to prevent redux-act
to throw between tests. To do so, you have a small API to manage types stored by redux-act
.
; // Add a type and prevent any action creator from using it from now ontypes;types; // Remove a type, you can use it again in an action creatortypes; // Test if a type is already usedtypes; // truetypes; // false // Check if a type is already used,// will throw TypeError if sotypes // throw TypeErrortypes // do nothing (return undefined) // Return all used typestypesall; // [ 'MY_TYPE' ] // Remove all typestypesclear; // Disable all type checking meaning you can now have several actions// with the same type. This is needed for HMR (Hot Module Replacement)// but never never never enable it in productiontypes; // Set back type checkingtypes;
Cookbook
Compatibility
redux-act
is fully compatible with any other Redux library, it just uses type
string after all.
⚠️ Warning It's important to remember that all redux-act
actions will store data inside the payload
property and that reducers will automatically extract it by default.
// Mixing basic and redux-act actions inside a reducer; // Standard Redux action using a string constantconst INCREMENT_TYPE = 'INCREMENT';const increment = type: INCREMENT_TYPE ; const decrement = ; const reducer = ; reducer; // truereducer; // true
// Using redux-act actions inside a basic reducer; // Standard Redux action using a string constantconst INCREMENT_TYPE = 'INCREMENT';const increment = type: INCREMENT_TYPE ; const decrement = ; { };
Adding and removing actions
Using the handlers object.
const handlers = {};const reducer = ;const store = ;const increment = ; handlersincrement = state + 1; ; // store.getState() === 1; // store.getState() === 2 deletehandlersincrement; ; // store.getState() === 2; // store.getState() === 2
Using the on
and off
functions of the reducer. Those functions will be available whatever pattern you used to create the reducer.
const reducer = ;const store = ;const increment = ; reducer; ; // store.getState() === 1; // store.getState() === 2 reducer; ; // store.getState() === 2; // store.getState() === 2
Using the on
and off
functions of the function factory when creating the reducer.
const store = );const increment = ;const reducer = ; store; ; // store.getState() === 1; // store.getState() === 2; // store.getState() === 3; // store.getState() === 3; // store.getState() === 3
Async actions
;;; const start = ;const success = ; const reducer = ; // 1) You can use the same way as the Redux samples// using thunk middlewareconst createStoreWithMiddleware = createStore; const store = ; { // We don't really need the dispatch // but here it is if you don't bind your actions return { // state: { running: false, result: false } ; // state: { running: true, result: false } return { // Here, you should probably do a real async call, // like, you know, XMLHttpRequest or Global.fetch stuff ; }; };} store; // 2) You can enjoy the redux-act binding// and directly call the actionsconst store = ; start;success; { // state: { running: false, result: false } ; // state: { running: true, result: false } return { // Here, you should probably do a real async call, // like, you know, XMLHttpRequest or Global.fetch stuff ; };} ;
Enable or disable batch
Since batch
is an action creator like any other, you can add and remove it from any reducer.
;const reducer = ; // Reducer no longer support batched actionsreducer; // Put it back using the reducer itself as the reduce functionreducer; // Be careful if 'payload' option is falsereduceroptions payload: false ;reducer;
TypeScript
We've built some basic typings around this API that will help TypeScript identify potential issues in your code.
You can use any of the existing methods to create reducers and TypeScript will work (as a superset of Javascript) but that kind of defeats some of the benefits of TypeScript. For this reason, the following is the recommended way to create a reducer.
; ; ; ; reducer.onadd,;
Using the reducer.on()
API, TypeScript will identify the payload set on add
and provide that type as payload. This can be really handy once your code starts scaling up.
Caveats
Due to some limitations on TypeScript typings, action creators have some limitations but you can create typed action creators assuming you have no payload reducer.
; ;;;
action
and emptyAction
will provide typing support, making sure action
is provided a boolean as first and only argument, or emptyAction
is not provided any argument at all.
otherAction
, on the otherhand, will be able to be called with any arguments, regardless of what the payload reducer expects.
Loggers
redux-act
provides improved logging with some loggers, mostly for batched actions.
Missing your favorite one? Please open an issue or a pull request, it will be added as soon as possible.
Redux Logger
;;; // Init loggerconst logger = ; // Same asconst logger = ; // Create the storeconst store = createStore/* reducer */;
Thanks
A big thank to both @gaearon for creating Redux and @AlexGalays for creating fluxx which I took a lot of inspiration from.
Tests
If you need to run the tests, just use npm test
or npm run coverage
if you want to generate the coverage report.
License
This software is licensed under the Apache 2 license, quoted below.
Copyright 2015 Paul Dijou (http://pauldijou.fr).
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.