Skip to content

Instantly share code, notes, and snippets.

@cvbuelow
Forked from gaearon/reducers.js
Last active July 25, 2019 11:10
Show Gist options
  • Save cvbuelow/ea7bd4deb7824fdb65d81cd2b8c60f5e to your computer and use it in GitHub Desktop.
Save cvbuelow/ea7bd4deb7824fdb65d81cd2b8c60f5e to your computer and use it in GitHub Desktop.
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