-
-
Save cvbuelow/ea7bd4deb7824fdb65d81cd2b8c60f5e to your computer and use it in GitHub Desktop.
Code splitting in Redux with SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) | |
} | |
}; | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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