Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure multiple HTTP requests in a server-side rendered React app?

I am currently using the below server side rendering logic (using reactjs + nodejs +redux) to fetch the data synchronously the first time and set it as initial state in store.

fetchInitialData.js

  export function fetchInitialData(q,callback){
      const url='http://....'
      axios.get(url)
          .then((response)=>{
              callback((response.data));
          }).catch((error)=> {
            console.log(error)
      })
  }

I fetch the data asynchronously and load the output in to store the first time the page loads using callback.

handleRender(req, res){
 fetchInitialData(q,apiResult => {
    const data=apiResult;
    const results ={data,fetched:true,fetching:false,queryValue:q}
    const store = configureStore(results, reduxRouterMiddleware);
     ....
    const html = renderToString(component);
    res.status(200);
    res.send(html);
    })
}

I have a requirement to make 4 to 5 API calls on initial page load hence thought of checking to see if there is an easy way to achieve making multiple calls on page load.

Do I need to chain the api calls and manually merge the response from different API calls and send it back to load the initial state?

Update 1: I am thinking of using axios.all approach, can someone let me know if that is a ideal approach?

like image 425
Learner Avatar asked Oct 20 '16 18:10

Learner


People also ask

Can React be rendered on server-side?

Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.

Is React client-side rendering or server-side rendering?

React along with other framework like angular and vue. js are traditional client side framework ,they run in browser but there are technology to run this framework on server side, and next. js is a solution for running react application server side.It also makes react development very simple.

Does ReactJS uses Phantomjs to render the webpage on server-side?

React JS uses phantom js to render the webpages on server-side b. React JS is a framework c. React JS improves the performance of the applications by using the concept of virtual DOM d. In React JS, the data flow will happen in a single direction 2.

Does React support SSR?

js is one of the most popular frameworks to set up SSR for a React application and Express is a great option for creating the HTTP server.


1 Answers

You want to make sure that requests happen in parallel, and not in sequence.

I have solved this previously by creating a Promise for each API call, and wait for all of them with axios.all(). The code below is basically pseudo code, I could dig into a better implementation at a later time.

handleRender(req, res){
  fetchInitialData()
    .then(initialResponse => {
      return axios.all(
        buildFirstCallResponse(),
        buildSecondCallResponse(),
        buildThirdCallResponse()
      )
    })
    .then(allResponses => res.send(renderToString(component)))
}

buildFirstCallResponse() {
  return axios.get('https://jsonplaceholder.typicode.com/posts/1')
    .catch(err => console.error('Something went wrong in the first call', err))
    .then(response => response.json())
}

Notice how all responses are bundled up into an array.

The Redux documentation goes into server-side rendering a bit, but you might already have seen that. redux.js.org/docs/recipes/ServerRendering

Also checkout the Promise docs to see exactly what .all() does.developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Let me know if anything is unclear.

like image 163
AntonNiklasson Avatar answered Oct 26 '22 11:10

AntonNiklasson