React - Fetch multiple apis

Viewed 4194

I want to make a get request to multiple apis at the same time from 2 different urls, and then I want to just update the array "items" in the state with the new property "img", not to overwrite it. I want to keep and properties in the first request. Here is my try.

   componentDidMount(){

      let url = ``;
      let url2 = ``

        fetch(url,{
          method: 'GET'
        })
        .then((response)=> response.json())
        .then((responseJson) => {
          const newItems = responseJson.items.map(i => {
            return{
              itemId: i.itemId,
              name: i.name,
            };
          })
          const newState = Object.assign({}, this.state, {
            items: newItems
          });

          console.log(newState);
          this.setState(newState);
        })
        .catch((error) => {
          console.log(error)
        });
        fetch(url2,{
          method: 'GET'
        })
        .then((response)=> response.json())
        .then((responseJson) => {
          const newImg = responseJson.item.map( data=> {
            return{
              img: data.picture.url
            };
          })
          const newState = Object.assign({}, this.state, {
            items: newImg
          });

          console.log(newState);
          this.setState(newState);
        })
        .catch((error) => {
          console.log(error)
        });
    }
3 Answers

You absolutely can call two seperate APIs. The problem that you are having is that the API call that is returning last is overwriting the data that was saved from the first API call. Here is the code that will fix this.

componentDidMount(){

  let api1 = `https://myapiexample1.com`;
  let api2 = `https://myapiexample2.com`;

  let promise1 = fetch(api1)
  .then(response => response.json())
  .then(json => json.items.map(item => {
    return {
      itemId: item.itemId
      name: item.name
    }
  }))

  let promise2 = fetch(api2)
  .then(response => response.json())
  .then(json => json.items.map(item => {
    return {
      img: item.img
    }
  }))

  Promise.all([promise1, promise2])
  .then(results => results[0].concat(results[1]))
  .then(items => this.setState({itmes}))
}

An alternative approach which is not as clean, but is similar to what you are currently doing is to make sure to include the old state when adding new items to the state:

this.setState({
  items: newItems.concat(this.state.items)
})
Related