I'm using react-router 2.0 on the server. Some of my top-level route components depend on async data to be fetched and uses Redux to manage state. To deal with this, I'm using a static fetchData()
method to return a Promise.all
of async actions as suggested in the official Redux docs. It works pretty well - the initial render from the server comes with the appropriate data in the Redux store.
My issue comes from how to write these async calls in a way that will work on both the initial render on the server and subsequent renders on the client as different routes get loaded. Currently, I make calls to the static fetchData()
method in my top-level component's componentDidMount()
, but this would cause the fetchData()
to be called once the component mounts on the client. This is what I want when navigating to the route from another, but not on the initial render as we already made this call on the server.
I've been struggling with writing my data fetching logic in a way that:
- Only gets called once on initial render on the server, not on the initial client render
- Will render when a user navigates in from another route.
I was thinking of injecting a prop like { serverRendered: true }
into the initial component but I only have access to the <RouterContext>
when calling renderToString()
. I took a peek at the source for but it doesn’t seem like I can pass the property from that JSX tag either.
I guess my questions would be:
- Is there a way to inject a property in
<RouterContext>
so that it passes down to the 'parent' top-level route component? If not in<RouterContext>
, is there another way to inject the property in? - If #1 isn't possible, is there a better way to handle
fetchData()
so the initial render won't causefetchData()
to be called on both the server and client?
{ serverRendered: true }
on page load and then turn it off afterwards. – BlackfellowfetchData()
method to for the initial server-side load, and checking incomponentDidMount()
whether the Redux data exists before making another call for the required data. It feels sloppy, but it works. If you ever come across a better method, please post it here! – Oligocene