Skip to content

Instantly share code, notes, and snippets.

@tomasswood
Created November 13, 2018 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasswood/befc0a396619e8881c49fd0da1c348cb to your computer and use it in GitHub Desktop.
Save tomasswood/befc0a396619e8881c49fd0da1c348cb to your computer and use it in GitHub Desktop.
Reuse the same redux reducer code for a different slice of state
/**
* Higher-order reducer factory for creating named reducers.
* Both params are required, and it will return your reducer or state.
*
* @param key
* @param reducer
* @returns {function}
*/
const createNamedReducer = (key, reducer) => {
return (state, action) => {
// Action must have a key called 'reducerName'. Use the optional metadata param with createAction
const { reducerName } = action;
const isInitialCall = state === undefined; // Check if initialization is happening
// If the provided key doesn't match the reducerName, and it's not the initialization, return the state
if (reducerName !== key && !isInitialCall) {
return state;
}
// Otherwise return the reducer
return reducer(state, action);
};
};
export default createNamedReducer;
const reducers = {
someOtherReducer,
[SLICE_1]: createNamedReducer(SLICE_1, reducer),
[SLICE_2]: createNamedReducer(SLICE_2, reducer),
[SLICE_3]: createNamedReducer(SLICE_3, reducer)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment