user3453133
user3453133

Reputation: 41

server side render with react router with data fetch

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

Upvotes: 1

Views: 2548

Answers (2)

Rodion
Rodion

Reputation: 521

If you are using Redux, take a look also to https://github.com/Rezonans/redux-async-connect It's similar to AsyncProps, but better fits for projects that uses Redux

Upvotes: 2

taion
taion

Reputation: 2837

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.

Upvotes: 1

Related Questions