Skip to content

Instantly share code, notes, and snippets.

@dagstuan
Last active September 7, 2018 11:39
Show Gist options
  • Save dagstuan/5c5a5fe00964676b0ef2ba1d4cd8911d to your computer and use it in GitHub Desktop.
Save dagstuan/5c5a5fe00964676b0ef2ba1d4cd8911d to your computer and use it in GitHub Desktop.
Store with injectReducer
import { applyMiddleware, createStore, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
const middlewares = [thunkMiddleware];
let composeEnhancers = compose;
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable no-underscore-dangle */
composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || composeEnhancers;
/* eslint-enable no-underscore-dangle */
}
const enhancer = composeEnhancers(applyMiddleware(...middlewares));
function getValues(obj) {
return Object.keys(obj).map(k => obj[k]);
}
function reduceReducers(...reducers) {
return (state, action) =>
reducers.reduce((prevState, reducer) => reducer(prevState, action), state);
}
const defaultReducer = reduceReducers(/* INSERT DEFAULT REDUCERS */);
export function injectReducer(store, name, newReducer) {
// eslint-disable-next-line no-param-reassign
store.reducers[name] = newReducer;
store.replaceReducer(reduceReducers(...getValues(store.reducers)));
}
export function configureStore() {
const createStoreWithMiddleware = enhancer(createStore);
const store = createStoreWithMiddleware(defaultReducer, {});
store.reducers = {
defaultReducer,
};
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment