ReactJS – use asynchronous update parameters React, setState?

Does anyone know whether the async updater parameter can be used in setState(updater) in React? I have the following code invalid (f is called, but the UI is not updated):

this.setState( async (prevState) => ({
foo : await f(prevState.someData)
}))

Obviously the async parameter is the problem. I had to use this ugly alternative version:

< pre>this.setState( async (prevState) => {
this.setState({
foo: await f(prevState.someData)
})
})

Is there a better way to write the above code?

Then you can setState twice.

this.setState((prevState) => {
f(prevState.someData);

// Don't change state now.
return {};
})

async f(someData) {
this.setState(prevState) {
// Do something
}
}< /pre>

Does anyone know whether it is possible to use the async updater parameter in setState(updater) in React? I have the following code invalid (f is called, but the UI is not updated):

this.setState( async (prevState) => ({
foo : await f(prevState.someData)
}))

Obviously the async parameter is the problem. I had to use this ugly alternative version:

< pre>this.setState( async (prevState) => {
this.setState({
foo: await f(prevState.someData)
})
})

Is there a better way to write the above code?

Then you can setState twice.

this.setState((prevState) = > {
f(prevState.someData);

// Don't change state now.
return {};
})

async f(someData) {
this.setState(prevState) {
// Do something
}
}

Leave a Comment

Your email address will not be published.