How to structure multiple HTTP requests in a server side React application?

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

fetchInitialData.js

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

I retrieve the data asynchronously and load the output into the repository the first time the page is loaded with a 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 when the page loads, so you need to check if there is an easy way to achieve multiple calls when the page loads.

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

Update 1: I'm thinking of using the axios.all approach, can someone let me know if this is the perfect approach?

+7
reactjs redux serverside-rendering
source share
3 answers

You want queries to run in parallel, not sequentially.

I solved this earlier by creating Promise for each API call, and waited for them all with axios.all() . The code below is basically pseudo-code, I could quickly recycle a more efficient implementation.

 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 embedded in the array.

The Redux documentation is slightly redrawn on the server side, but you may have already seen this. redux.js.org/docs/recipes/ServerRendering

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

Let me know if something is unclear.

+6
source

You can try express-batch or GraphQL is another option.

0
source

You can also use Redux-Sagas to use pure Redux actions to launch multiple api calls and handle all these calls using pure actions. Meet the Sagas

0
source

All Articles