Skip to content

Instantly share code, notes, and snippets.

@DJCordhose
Created September 20, 2015 11:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DJCordhose/68fe2ddca6d9ba595534 to your computer and use it in GitHub Desktop.
Save DJCordhose/68fe2ddca6d9ba595534 to your computer and use it in GitHub Desktop.
React-redux-router: How to wait until all required actions have finished before rendering on the server side
export default function renderRoute(request, reply) {
const store = configureStore();
store.dispatch(match(request.path, (error, redirectLocation, routerState) => {
if (redirectLocation) {
reply.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
reply(error.message).code(500);
} else if (!routerState) {
reply('Not found').code(404);
} else {
// Promise.all in preRender waits until all Promises from the Components are resolved and only then starts to render the result.
preRender(store, routerState).then(() => {
const routes = getRoutes(store.getState);
const html = renderToString(
<Provider store={store}>
<ReduxRouter routes={routes}/>
</Provider>
);
const initialData = store.getState();
const fullPage = renderFullPage(html, initialData);
const response = reply(fullPage);
response.type('text/html');
}).catch((error) => reply(error).code(500));
}
}));
}
function preRender(store, routerState) {
const promises = routerState.components.map(component => (component && component.preRender) ?
component.preRender(store, routerState) : null).filter(component => !!component);
return Promise.all(promises);
}
// Sample code of a container components which just executes on action that returns a promise.
// Note that this could be many actions that could also be executed in a specific order - using promises - if you wanted to
// and that you can get access to whatever you need from the routerState
component.preRender = (store, routerState) => store.dispatch(Actions.loadVote(routerState.params.id));
// more info here
https://github.com/gaearon/redux-thunk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment