0

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)
        });
    }
2
  • Add what issues you're facing and your best approximation of where it's happening. Commented Sep 3, 2018 at 13:48
  • I mentioned what I'm facing above, the problem is in the const newState, Object.assign is just assigning and overwrite not appending Commented Sep 3, 2018 at 13:52

2 Answers 2

1

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);
})
Sign up to request clarification or add additional context in comments.

Comments

0

use EC6 Spread operator

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.