Created
February 7, 2018 00:13
-
-
Save gabemeola/d3099d2908aeca353e0b48f9d41135b6 to your computer and use it in GitHub Desktop.
Create a reducer with the cruft cut off
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Creates a reducer with generic reducer logic handle for you. | |
* For any cases not matched from an `action.type`, the passed state is returned. | |
* | |
* @author Gabe M. | |
* @param {string} name - Name of the Reducer. Redux will use this for store and serialization | |
* @param {Object} initialState - Initial State Object | |
* @param {Object} cases - Cases is an object with describe your mutations. | |
* Key is a matching action.type from a dispatched action. | |
* Value is a function that accepts state, and action. This should return new non mutated state. | |
* | |
* | |
* @example | |
* createReducer('myReducer', { name: 'gabe' }, { | |
* 'UPDATE_NAME': (state, action) => ({ | |
* ...state, | |
* name: action.payload, | |
* }) | |
* }) | |
* | |
* | |
* @return {function(state, action)} genericReducer - Returns a Reducer function | |
*/ | |
function createReducer(name, initialState, cases) { | |
function genericReducer(state = initialState, action) { | |
if (action.type in cases) { | |
return cases[action.type](state, action); | |
} | |
return state; | |
} | |
genericReducer.reducerName = name; | |
return genericReducer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment