简体   繁体   中英

React Server Side Rendering with expensive initial API call

I am now experiencing a problem with react SSR. Basically I am building a universal React App, upon sending the initial request from the browser, server should prepare all the necessary data and call renderToString() to pass the rendered HTML to user.

In my server side code, I have something like:

fetchInitialData().then((response) => renderToString(...))

As you can see it, the server will wait fetchInitialData to be finished then it can send the rendered HTML. However, the problem here is that the fetchInitialData takes a long time to finish, that means on the client side user will see a blank screen until server finishes that initial API call.

My question is is there any way for server to send a loading page to user, when it finishes the API call, update the loading screen with the actual data?

====== One solution I can think of is to let server straight send the loading page to user, then user calls that API in componentDidMount() Please advise if you have a better one

I am answering this question for myself.

If anyone is also experiencing this issue, you can consider use the bigpipe technology developed by facebook.

The whole idea is that server still sends the html, but everything without < /body > and < /html >. So it is actually an unclosed html. upon the receipt of < script>, client will execute it immediately, that means client and server are both doing its jobs, no one is wasting time.

In terms of implementation, assuming you are using NodeJS:

app.use('/', (req, res) => {
  res.write(templateHTML); // this has unclosed HTML and all scripts

  // doing expensive API call here
  result = API.call()
  // if code runs here, we get response from API call
  res.write(result + '</body></html>');
  res.end();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM