S
S
Shaks2017-07-02 11:02:43
React
Shaks, 2017-07-02 11:02:43

How to correctly load data in server rendering + react router v4?

Pilu isomorphic/universal application. I do not quite understand how to work with the data.
In my server.js, in order for the props to be filled with data before rendering, I implemented this:

routes.some(route => {
        const match = matchPath(req.url, route);
        if (match && typeof route.loadData === "function"){
            promises.push(store.dispatch(route.loadData()));
        }

        return match
    });

    Promise.all(promises).then(() => {
// после того как получил все данные - делаю рендер
}

After the layout with the content is given to the browser, the client-side rendering of the components is triggered. And here is where I have a snag.
When a component mounts, it must load data from the backend server. But this loading was already implemented on the server just a moment ago (provided that the transition to this component was not implemented through the react router, but through ctrl + r for example).
The question is how to avoid repeated requests to the backend from the client (if there was a request from the front-end server), and is it worth it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-07-02
@iNikNik

You need to save the information that the data has been loaded in any convenient way. This can be done both at the bootloader level

// что-то вроде этого
promises.push(
  store
    .dispatch(route.loadData())
    .then(() => store.dispatch(dataForRouteLoaded(req.url))
)

And later, on the client side, check the flag. In this case, you will most likely need to make a separate component (HOC) for loading data - in order to do such a check in one place:
Or, in each specific action, check whether there is the required data in the state before loading it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question