Created
September 25, 2018 06:29
-
-
Save jzDev/ffb7802b6922effe6d5b6b5dfcd5a0dd to your computer and use it in GitHub Desktop.
Redux reducer registry to dynamically add reducers
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 placeholderReducer = (state = null) => state; | |
let reducers = {}; | |
export default { | |
getReducers() { | |
return { ...reducers }; | |
}, | |
// Preserve initial state for not-yet-loaded reducers | |
getInitialReducer(initialReducers, initialState) { | |
const reducerNames = Object.keys(initialReducers); | |
reducers = { ...initialReducers }; | |
Object.keys(initialState).forEach(key => { | |
if (reducerNames.indexOf(key) === -1) { | |
reducers[key] = placeholderReducer; | |
} | |
}); | |
return this.getReducers(); | |
}, | |
register(reducer, reducerName = reducer.name) { | |
const existingReducer = reducers[reducerName]; | |
if (existingReducer && existingReducer !== placeholderReducer) { | |
return; | |
} | |
reducers = { | |
...reducers, | |
[reducerName]: reducer, | |
}; | |
if (this.onRegisterHandler) { | |
this.onRegisterHandler(this.getReducers()); | |
} | |
}, | |
onRegister(cb) { | |
this.onRegisterHandler = cb; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based off of the Twitter implementation referenced @ http://nicolasgallagher.com/redux-modules-and-code-splitting/