Ad

Server Side Render With React Router With Data Fetch

- 1 answer

I'm in the process of upgrading to version 1 of React Router and can't get the data fetching side of my code to work on the server, i.e. initial server-side render.

What I am trying to do is fetch data from the server depending on the selected route. Each component has a static fetchData method and along with a global data method I build up the data to then pass into the controller view component defined in the route config.

My code is below:

match({routes, location: req.url}, (err, redirectLocation, renderProps) => {

  fetchData(renderProps).then((data) => {
      //page specific data
      return data;
    }).then((data) => {
      //global data
      getGlobalData().then((appData) => {

        data.app = appData;

        data = Immutable.fromJS(data);

        let templateLocals = {
          "data": data
        };    console.log('trying to render');
      templateLocals.content = renderToString(
    <RoutingContext {...renderProps} data={data}/>
  );
  res.send(layout(templateLocals));
    });

  });
});

What I would like to do as before with <Handler> pre V1.0 is pass my data as props into the app (I can see that the data is correct and there as I pass it into the RoutingContext component). But what I see from RoutingContext module is that the implementation will not allow this. It only picks up history,location,params,route,routeParams,routes and not any custom props.

The example of server side render does not go this far, but am keen to understand how I should handle such an example as I upgrade?

Thanks in advance

Ad

Answer

Take a look at the async-props repo, which provides both an example as well as utilities for handling this sort of data fetching isomorphically: https://github.com/rackt/async-props.

Ad
source: stackoverflow.com
Ad