Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created February 7, 2018 00:13
Show Gist options
  • Save gabemeola/d3099d2908aeca353e0b48f9d41135b6 to your computer and use it in GitHub Desktop.
Save gabemeola/d3099d2908aeca353e0b48f9d41135b6 to your computer and use it in GitHub Desktop.
Create a reducer with the cruft cut off
/**
* 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