3

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

3
  • You can create a simplified (fading) HTML content of the expected result (just for the part that fits in your screen) and hard-code that content in your page. After the fetch you can replace the fake content in one replace action by the real data. Commented May 5, 2017 at 19:32
  • @JeroenHeier thats what I want to do actually. But how does server replace the hard-coded content with the actual one? my thought is that after server calls res.send(html), it has no control to that piece any more Commented May 5, 2017 at 19:39
  • Maybe this can help you. Commented May 5, 2017 at 19:50

1 Answer 1

3

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.