I am struggalling to understand the below case. This is my expactations here:
Once the getRegions() would be executed (there is an API call made there), then the data would be taken from the response.
The state would set as it is first awaited and then only set.
Console.log should log out
State is + the datafrom 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.
awaitis not a promise, so code execution is not awaiting the promise you created above that statement.awaitthe call togetRegions(...).then(...).catch(...);So the returned object is a promise. There is nodataproperty on a promise object, so it'sundefined.const { data } = await getRegions(e.target.value)it still doesn't work.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 yourawaitto yieldundefinedinstead of the object you want.