Created
November 13, 2018 21:36
-
-
Save tomasswood/befc0a396619e8881c49fd0da1c348cb to your computer and use it in GitHub Desktop.
Reuse the same redux reducer code for a different slice of state
This file contains 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
/** | |
* 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; |
This file contains 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
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