Skip to content

Instantly share code, notes, and snippets.

@sudheerDev
Last active September 5, 2023 03:22
Show Gist options
  • Save sudheerDev/303182c6043ea88c16ea900b0fc46fb5 to your computer and use it in GitHub Desktop.
Save sudheerDev/303182c6043ea88c16ea900b0fc46fb5 to your computer and use it in GitHub Desktop.
replaceReducer example
// This part of code is copied from Dan Abramov answer - https://stackoverflow.com/a/33044701/2902013
import { combineReducers } from 'redux';
import { createStore } from 'redux';
//couple of reducers available as part of inital config of app.
import users from './reducers/users';
import posts from './reducers/posts';
function createReducer(asyncReducers) {
return combineReducers({
users,
posts,
...asyncReducers
});
}
function configureStore(initialState) {
const store = createStore(createReducer(), initialState);
store.asyncReducers = {};
return store;
}
function injectAsyncReducer(store, name, asyncReducer) {
store.asyncReducers[name] = asyncReducer;
store.replaceReducer(createReducer(store.asyncReducers));
}
// Assuming React Router here but the principle is the same
// regardless of the library: make sure store is available
// when you want to require.ensure() your reducer so you can call
// injectAsyncReducer(store, name, reducer).
function createRoutes(store) {
// ...
const CommentsRoute = {
// ...
getComponents(location, callback) {
require.ensure([
'./pages/Comments',
'./reducers/comments'
], function (require) {
const Comments = require('./pages/Comments').default;
const commentsReducer = require('./reducers/comments').default;
injectAsyncReducer(store, 'comments', commentsReducer);
callback(null, Comments);
})
}
};
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment