wlsonf
wlsonf

Reputation: 51

Axios Async-Await in React

I'm trying to do some get, and post request, somehow the state got updated late (it should be .get, then .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;
}

the state got updated, but somehow the post got error that destination should be filled. I find the solution of this is to use async await. I try to implement it but it doesn't work.

here's what i've tried

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

i tried to console log the state of destination and yes it's indeed updated. am i doing async await wrong? thank you for your help!

Upvotes: 1

Views: 2971

Answers (1)

Garry
Garry

Reputation: 534

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

If you want to use post outside if its upto you.

Upvotes: 2

Related Questions