Выполнение двух вызовов в одной и той же функции - PullRequest
0 голосов
/ 21 января 2019

У меня есть два запроса: GET и POST, я получаю запрос GET и устанавливаю состояние ответа внутри и массив, и я хочу передать этот массив в тело запроса POST, затем я получаю запрос POST поэтому я могу сделать вызов, проблема в том, что он не устанавливает состояние в вызове GET и всегда возвращает неопределенное значение, и я не могу понять, почему, вот код:

Мой конструктор:

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

Функция:

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));
};

1 Ответ

0 голосов
/ 21 января 2019

вы забыли вернуть обещание, затем используйте объект response, чтобы установить поле infoID, а не состояние, так как вызов this.setState является асинхронным и будет оставаться в ожидании, когда вы сделаете второй вызов API.

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));
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...