Skip to content

Instantly share code, notes, and snippets.

@kiruh
Created August 2, 2019 10:47
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 kiruh/7db5797105745cddd2de8d1a8dadfa42 to your computer and use it in GitHub Desktop.
Save kiruh/7db5797105745cddd2de8d1a8dadfa42 to your computer and use it in GitHub Desktop.
Combine root reducer with nested reducers
const combineRootWithReducers = ({
root = () => ({}), // reducer which should be on the root level of global state
reducers = {}, // other reducers
initial = {}, // initial state of global state
rootLast = false // if true, root reducer will be called after other reducers
}) => {
/*
this method allows you to combine basic reducers with a reducer which
manages state on the root level of global state
{
banana: ..., // first reducer
apple: ..., // second reducer
authUser: ..., // some value managed by root reducer
}
** notes **
- keys of root values and keys of reducers should be distinct
*/
const combined = (state = initial, action) => {
let nextState = { ...state };
const rootWrapper = x => root(x, action);
const reducersWrapper = x =>
Object.entries(reducers).reduce(
(ns, [name, reducer]) => ({
...ns,
[name]: reducer(ns[name], action)
}),
x
);
if (!rootLast) {
nextState = rootWrapper(nextState);
nextState = reducersWrapper(nextState);
} else {
nextState = reducersWrapper(nextState);
nextState = rootWrapper(nextState);
}
return nextState;
};
return combined;
};
export default combineRootWithReducers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment