create-reducer-redux
Create simple and functional reducers that can listen to multiple action creators.
Installation
npm i -S create-reducer-redux
Usage
Actions need to follow a convention of {type, data}
, where type
is the action type
being fired, and data
is the data associated with the action (if there is any). Otherwise,
we can omit the data
key.
const AuthActionCreators = { // Pretend we succesfully logged in return type: ActionTypesLOGIN_SUCCESS data: currentUser: user ; } { return type: ActionTypesLOGOUT_SUCCESS ; } // ...;
In your reducer, must provide a name
and handlers
key. An action handler can listen to multiple actions being fired if necessary.
// src/reducers/AuthReducer.js // Alternate import: `import {createReducer} from 'create-reducer-redux;`; // Always provide an initial state to begin withconst initialState = authError: null currentUser: null; initialState name: 'Authentication' handlers: onLogin: ActionTypesLOGIN_SUCCESS onLogout: ActionTypesLOGOUT_SUCCESS ActionTypesTOKEN_EXPIRED ActionTypesBLACKLISTED // ... Other actions that trigger a logout // Action handlers receive the current state and the `data` key from the action fired // as arguments. You must return a new (altered or unaltered) state from each action creator { return ...state currentUser: datacurrentUser; } // Here is an example of an action handler listening to multiple actions { return initialState; } ;
Immutable.js
I highly recommend pairing create-reducer-redux
with Immutable.js. Immtuable.js provides immutable datatypes to ensure that
actions handlers don't cause side effects.
The usage is indentical:
// Immutable.js Example ;; // Always provide an initial state to begin withconst initialState = Immutable; initialState name: 'Authentication' handlers: onLogin: ActionTypesLOGIN_SUCCESS onLogout: ActionTypesLOGOUT_SUCCESS ActionTypesTOKEN_EXPIRED ActionTypesBLACKLISTED // ... Other actions that trigger a logout // Action handlers receive the current state and the `data` key from the action fired // as arguments. You must return a new (altered or unaltered) state from each action creator { return state; } // Here is an example of an action handler listening to multiple actions { return initialState; } ;
createConstants
create-redux-reducer
also provides a convenient way for you to create clean and legible action type constants:
; const actionTypes = ; // This will become: // const actionTypes = {// 'HELLO': 'HELLO',// 'THERE': 'THERE',// 'WORLD': 'WORLD'// };