Skip to content

Instantly share code, notes, and snippets.

@sagiavinash
Last active July 31, 2018 11:24
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 sagiavinash/4b07334bd46fa56b79182f6a3c027b0a to your computer and use it in GitHub Desktop.
Save sagiavinash/4b07334bd46fa56b79182f6a3c027b0a to your computer and use it in GitHub Desktop.
import { createStore, combineReducers } from 'redux';
const reduceReducers = (reducers) => (state, action) =>
reducers.reduce((result, reducer) => (
reducer(result, action)
), state);
export const storeManager = {
store: null,
reducerMap: {},
registerReducers(reducerMap) {
Object.entries(reducerMap).forEach(([name, reducer]) => {
if (!this.reducerMap[name]) this.reducerMap[name] = [];
this.reducerMap[name].push(reducer);
});
},
createRootReducer() {
return (
combineReducers(Object.keys(this.reducerMap).reduce((result, key) => Object.assign(result, {
[key]: reduceReducers(this.reducerMap[key]),
}), {}))
);
},
createStore(...args) {
this.store = createStore(this.createRootReducer(), ...args);
return this.store;
},
refreshStore() {
this.store.replaceReducer(this.createRootReducer());
},
};
export const withRefreshedStore = (importPromise) => (
importPromise
.then((module) => {
storeManager.refreshStore();
return module;
},
(error) => {
throw error;
})
);
export default storeManager;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment