Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code splitting in Redux with SSR
import { combineReducers } from 'redux';
import users from './reducers/users';
import posts from './reducers/posts';
// Inject the initial state for async loaded reducers
function injectState(reducers, preloadedState = {}) {
return Object.keys(reducers).reduce((finalReducers, key) => {
if (typeof reducers[key] === "function") {
finalReducers[key] = (state = preloadedState[key], action) => reducers[key](state, action);
}
return finalReducers;
}, {});
}
export default function createReducer(asyncReducers, preloadedState) {
return combineReducers(injectState({
users,
posts,
...asyncReducers
}, preloadedState));
}
export default function createRoutes(store) {
// ...
const CommentsRoute = {
// ...
getComponents(location, callback) {
require.ensure([
'./pages/Comments',
'./reducers/comments'
], function (require) {
store.injectReducer({
comments: require('./reducers/comments').default
});
callback(null, require('./pages/Comments').default);
})
}
};
// ...
}
import { createStore } from 'redux';
import createReducer from './reducers';
export default function configureStore(preloadedState) {
let asyncReducers = {};
const store = createStore(createReducer(), preloadedState);
store.injectReducer = (reducer) => {
const newReducers = {
...reducer,
...asyncReducers
};
if (Object.keys(newReducers).length !== Object.keys(asyncReducers).length) {
asyncReducers = newReducers;
store.replaceReducer(createReducer(asyncReducers, preloadedState));
}
};
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment