In a component I would like fetch some data from my database using fetch API. When all the data is fetched I would like to change the state of the component using Promise.all():
await Promise.all(data).then(
this.setState({
isLoading: false
})
)
My problem is that setState() fires before the Promises are resolved. However this code works but then isLoading is an array instead of boolean:
this.setState({
isLoading: await Promise.all(data)
})
Does anyone know why? I'm kinda new to React-Native so would love some input!
As you are using async
/ await
, you shouldn't call then
at all. If you still wanted to use it, you'd need to pass a callback; but your code really should simply look like the following:
await Promise.all(data);
this.setState({
isLoading: false
});
You should change like this:
await Promise.all(data).then((result) => {
this.setState({
isLoading: false
})
}
)
Basically .then
has a function as parameter so you have to put your setState
inside an arrow function.
then(
this.setState(...)
)
You're calling setState()
immediately and passing its result to then()
(just like any other function call).
You need to pass a function or lambda to then()
that calls setState
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.