Skip to content

Instantly share code, notes, and snippets.

@jzDev
Created September 25, 2018 06:29
Show Gist options
  • Save jzDev/ffb7802b6922effe6d5b6b5dfcd5a0dd to your computer and use it in GitHub Desktop.
Save jzDev/ffb7802b6922effe6d5b6b5dfcd5a0dd to your computer and use it in GitHub Desktop.
Redux reducer registry to dynamically add reducers
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;
}
};
@jzDev
Copy link
Author

jzDev commented Sep 25, 2018

Based off of the Twitter implementation referenced @ http://nicolasgallagher.com/redux-modules-and-code-splitting/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment