Skip to content Skip to sidebar Skip to footer

React - Combine Data Returned Two Api Calls And Set State Of An Array With These Values

I am making two GET requests to two different urls, which return different pieces of data. I am then trying to set the values returned to the value of an array, called artists. I a

Solution 1:

You can use the Promise.all() method to await resolution of all the promises then deal with the results in one go. This also means you are only calling setState() once, stopping unnecessary re-rendering of the component.

componentDidMount: function() {
  const requestOne = $.get(PostsOneURL);
  const requestTwo = $.get(PostsTwoURL);

  Promise.all([requestOne,requestTwo])
    .then(requestData => {
      this.setState({
        artists: requestData.map(data => data.result.posts)
        isLoaded: true
      )}
    });
}

Solution 2:

I'm not an expert in react but I can help you with that. Just use https://www.npmjs.com/package/redux-promise if you are using redux, and it will deliver the resolved value for you without anything from your part. It's a middleware that guarantees that nothing will reach the reducers without being resolved. On the other hand, if you are using vanilla react, you could deal with them yourself creating your own middlewares, but you need to make sure that the values reach the reducers resolved to produce the proper state. For this second approach you just wait the promise to resolve and then execute a dispatch to go back to the beggining of the middleware chain and on that second execution of the middlewares the value will be resolved.

Just remember not to mutate the state, generate a new object {...state, thingsyouwanttoadd }.

P.S: I also recommend to take the Stephen Grider courses on Udemy, really good stuff and he does exactly what you are trying to do here on this course https://www.udemy.com/react-redux/ , he waits for the values to resolve with that library and then he displays it .


Post a Comment for "React - Combine Data Returned Two Api Calls And Set State Of An Array With These Values"