Axios Async-Await in React - PullRequest
       13

Axios Async-Await in React

0 голосов
/ 29 мая 2019

Я пытаюсь выполнить запрос get и post, каким-то образом состояние обновилось поздно (должно быть .get, затем .post)

async componentDidMount() {

    const {destination, weight} = this.state;


    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}

состояние обновлено, но как-то в сообщении появилась ошибка, что место назначения должно быть заполнено. Я считаю, что решение этой проблемы заключается в использовании асинхронного ожидания. Я пытаюсь реализовать это, но это не работает.

вот что я пробовал

async componentDidMount() {

        const {destination, weight} = this.state;


        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}

Я попытался утешить журнал о состоянии назначения, и да, оно действительно обновлено. я делаю асинхронное ожидание неправильно? спасибо за вашу помощь!

1 Ответ

2 голосов
/ 29 мая 2019
try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}

Если вы хотите использовать пост снаружи, если это до вас.

...