Mary Jane
Mary Jane

Reputation: 173

Making two calls in same function

I have two requests a GET and a POST request, I'm fetching the GET request and setting the response state inside and array and I want to pass this array to the POST request body, then I'm fetching the POST request so I can make the call, the problem is that it's not setting the state in the GET call and it's always returning undefined and i can't figure out why, here is the code:

My constructor:

constructor(props){
  super(props);
  this.state = {
    info: [],
  }
}

Function:

myFunction = async () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response });
      fetch("https://myapp.com/submit_info", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: this.state.info.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};

Upvotes: 0

Views: 128

Answers (1)

Karim
Karim

Reputation: 8652

you forgot to return the promise, then use the response object to set the infoID field and not the state cause the call to this.setState is asynchronous and will still be pending when you make the second api call.

myFunction = () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response }); // async call
      return fetch("https://myapp.com/submit_info", {
        // return promise for chaining
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: response.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};

Upvotes: 2

Related Questions