Created
August 2, 2019 10:47
-
-
Save kiruh/7db5797105745cddd2de8d1a8dadfa42 to your computer and use it in GitHub Desktop.
Combine root reducer with nested reducers
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
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