Skip to content

Instantly share code, notes, and snippets.

@alexnm
Created March 25, 2018 16:50
Show Gist options
  • Save alexnm/baa5fa6a73d434d60a643c4a840efd9a to your computer and use it in GitHub Desktop.
Save alexnm/baa5fa6a73d434d60a643c4a840efd9a to your computer and use it in GitHub Desktop.
Complete example with data fetched on the server
/* ... */
import { StaticRouter, matchPath } from "react-router-dom";
import routes from "./routes";
/* ... */
app.get( "/*", ( req, res ) => {
/* ... */
const dataRequirements =
routes
.filter( route => matchPath( req.url, route ) ) // filter matching paths
.map( route => route.component ) // map to components
.filter( comp => comp.serverFetch ) // check if components have data requirement
.map( comp => store.dispatch( comp.serverFetch( ) ) ); // dispatch data requirement
Promise.all( dataRequirements ).then( ( ) => {
const jsx = (
<ReduxProvider store={ store }>
<StaticRouter context={ context } location={ req.url }>
<Layout />
</StaticRouter>
</ReduxProvider>
);
const reactDom = renderToString( jsx );
const reduxState = store.getState( );
res.writeHead( 200, { "Content-Type": "text/html" } );
res.end( htmlTemplate( reactDom, reduxState ) );
} );
} );
/* ... */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment