React setState with async update option?

Does anyone know if React can use the async updater parameter in setState(updater)? I have the following code that does not work (called f, but the user interface is not updated):

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

Apparently, the parameter asyncis 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?

+4
source share
3 answers

Then you can setStatetwice.

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

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

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

I assume that you are calling setState for the method. So why not put async on the method?

async handleSomething () {
  //.. some logic

  this.setState(prevState => ({
    foo: await f(prevState.someData)
  }))
}
Run code
0

You cannot use async inside setState, as setState should be a pure function without side effects. Just execute the async method before calling setState:

async classMethod = () => {
    let response = await someAsyncOperation(this.state.someData);
    this.setState({ someData: response });
}
-1
source

Source: https://habr.com/ru/post/1680209/


All Articles