Skip to content

Instantly share code, notes, and snippets.

@jpgorman
Last active September 20, 2018 14:48
Show Gist options
  • Save jpgorman/c1385fd3ddf323303e26bfb2bb1dead1 to your computer and use it in GitHub Desktop.
Save jpgorman/c1385fd3ddf323303e26bfb2bb1dead1 to your computer and use it in GitHub Desktop.
// store.js
import * as redux form 'redux'
const { createStore, combineReducers } = redux
// export our createStore function
export default reducerMap => {
const injectAsyncReducers = (store, name, reducers) => {
// add our new reducers under the name we provide
store.asyncReducers[name] = combineReducers(reducers);
// replace all of the reducers in the store, including our new ones
store.replaceReducer(
combineReducers({
...reducerMap,
...store.asyncReducers
})
);
};
// create the initial store using the initial reducers that passed in
const store = createStore(combineReducers(reducerMap));
// create a namespace that will later be filled with new reducers
store.asyncReducers = {};
// add the method that will allow us to add new reducers under a given namespace
store.registerDynamicModule = ({ name, reducers }) => {
console.info(`Registering module reducers for ${name}`);
injectAsyncReducers(store, name, reducers);
};
// add a method to unhook our reducers. This stops our reducer state from updating any more.
store.unRegisterDynamicModule = name => {
console.info(`Unregistering module reducers for ${name}`);
const noopReducer = (state = {}) => state;
injectAsyncReducers(store, name, noopReducer);
};
// return our augmented store object
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment