I'm facing an issue on how to update store when a react-router transition occurs.
In my current implementation (below), update store before rendering next page. The issue comes up when the current page gets a store update based on the data for the next page: (1) the current page renders pointlessly (it's subscribed to store updates), because the updated store is for the next page (2) the current page breaks on render because updated store only has data for the next page.
superagent
.get(opts.path)
.set('Accept', 'application/json')
.end((err, res) => {
let pageData = res && res.body || {};
store.dispatch(setPageStore(pageData));
render(store);
});
The reverse is problematic too, render next page before updating store. The issue now is the next page breaks on render because the data needed for the next page is not there until store is updated.
I'm either misusing the libraries, or my architecture is incomplete, or something else. help!
The rest of the sample code:
app
const React = require('react');
const Router = require('react-router');
const {createStore} = require('redux');
const {update} = React.addons;
const routes = require('./routes'); // all the routes
let store = {};
let initialLoad = true;
Router.run(routes, Router.HistoryLocation, (Handler, opts) => {
if(initialLoad) {
initialLoad = false;
// hydrate
const initialState = JSON.parse(document.getElementById('initial-state').text);
store = createStore(appReducer, initialState);
render(store);
} else {
superagent
.get(opts.path)
.set('Accept', 'application/json')
.end((err, res) => {
let pageData = res && res.body || {};
store.dispatch(setPageStore(pageData));
render(store);
});
}
});
function render(store) {
React.render(
<Provider store={store} children={() => <Handler/>} />,
document.getElementById('react')
);
}
action & reducer
function appReducer(state = {}, action) {
switch(action.type) {
case 'SET_PAGE_STORE':
return update(state, {$merge: action.pageData});
default:
return reduce(state, action);
}
}
const reduce = combineReducers({
// ..all the reducers
});
function setPageStore(pageData) {
return {type: 'SET_PAGE_STORE', pageData};
}