develop05
develop05

Reputation: 485

React - fetch multiple get requests

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'm looking for way to just append it. I want to keep the properties from 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)
        });
    }

Upvotes: 0

Views: 1695

Answers (2)

Aukta
Aukta

Reputation: 403

use EC6 Spread operator

this.setState({ items: { ...this.state.items, newItems } });

Upvotes: 0

Sergio Escudero
Sergio Escudero

Reputation: 1894

You can use Promise.all method more info here. For example:

const p1 = fetch(url,{
          method: 'GET'
        })
const p2 = fetch(url2,{
          method: 'GET'
        })

Promise.all([p1, p2]).then(values => { 
// here you have an array of reponses
  console.log(values);
})

Upvotes: 1

Related Questions