Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, setState with async updater parameter?

Does anybody know if in React it's possible to use an async updater parameter in setState(updater) ? I have the following code which is not working (f is called but the UI is not updated):

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

Apparently the async parameter is a problem. I had to use this ugly alternate version:

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

Is there a better way to write the above code?

like image 225
nino.porcino Avatar asked Nov 18 '22 17:11

nino.porcino


1 Answers

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
  }
} 
like image 66
Trantor Liu Avatar answered May 24 '23 14:05

Trantor Liu