0

I am struggalling to understand the below case. This is my expactations here:

  1. Once the getRegions() would be executed (there is an API call made there), then the data would be taken from the response.

  2. The state would set as it is first awaited and then only set.

  3. Console.log should log out State is + the data from the region.

     handleRegion = async (e) => {
       const { data } = getRegions(e.target.value)
         .then(function (done) {
           console.log("done");
         })
         .catch(function (error) {
           console.log("error");
         });
       await this.setState({ region: data });
       console.log("state is: " + this.state.region);
     };
    

Instead it first Executes the State is: undefiened and only then it is writting done.

Ideally I wanted the code to be written as:

  handleRegion = async (e) => {
    const { data } = await getRegions(e.target.value)         
    await this.setState({ region: data });
  };

The event is comming from a DDL list

 <select
                        className="form-control optiontpicker option-design"
                        name="area"
                        onChange={this.handleRegion}
                      >

So every time the DDL would be chaanged this function should beexecuted in this order.

5
  • In the first code block, the expression after your await is not a promise, so code execution is not awaiting the promise you created above that statement. Commented Oct 18, 2020 at 7:54
  • Which ones? The one from API call getRegions? The setState as far as I am aware returns a promise. How do I change the code? How do you see that it is not returning a Promise, still trying to grasp this topic. Commented Oct 18, 2020 at 7:56
  • You didn't await the call to getRegions(...).then(...).catch(...); So the returned object is a promise. There is no data property on a promise object, so it's undefined. Commented Oct 18, 2020 at 7:59
  • if I do this: const { data } = await getRegions(e.target.value) it still doesn't work. Commented Oct 18, 2020 at 8:01
  • @RaitisLebedevs trincot is correct, nothing in the React documentation suggests that this.setState() returns a promise, so awaiting it will probably not wait for the state to update. The other thing is that your .then() callback doesn't have a return value so it will cause your await to yield undefined instead of the object you want. Commented Oct 18, 2020 at 8:04

3 Answers 3

2

Two things that you did wrong 1. you did not add await before getRegions. and 2. You added await before setState. Why those two things are wrong? SetState is asynchronous but it does not return a promise. Await works only with promises.

handleRegion = async (e) => {
   const { data } = await getRegions(e.target.value)
       console.log("done");
   this.setState({ region: data },()=>{
        console.log("state is: " + this.state.region);
});
 
 };
Sign up to request clarification or add additional context in comments.

Comments

0

setState is asynchronous but it is not Promise actually. So you cannot use await and setState together. You have to use callback instead, or promisify setState to use with await.

handleRegion = async (e) => {
   const { data } = await getRegions(e.target.value)         
   this.setState({ region: data }, () => {
     console.log("state is: " + this.state.region);
   });
 };```

Comments

0

setState is asynchronous in nature, but it does not return a promise. Instead it calls your callback if you provide it as argument.

As you write that ideally you want to use await with it, you could promisify setState as follows:

promiseState = newState => 
    new Promise(resolve => this.setState(newState, resolve));

Then you can write the following code:

handleRegion = async (e) => {
    const { data } = await getRegions(e.target.value)         
    await promiseState({ region: data });
};

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.