How to use Async / Await with React hooks?

Yogi Katba picture Yogi Katba · Jun 14, 2020 · Viewed 11.5k times · Source

I am learning React and following a video tutorial. The instructor used class components and I'm using functional components to brush up on hooks concept.

I want to convert this code into a functional one:

return(
      <div className={classes.editorContainer}>
        <ReactQuill 
          value={this.state.text} 
          onChange={this.updateBody}>
        </ReactQuill>
      </div>
    );
  }
  updateBody = async (val) => {
    await this.setState({ text: val });
    this.update();
  };

I have tried to do this but async doesn't seem to work as I expected. Await is not working for setText.

const [text, setText] = useState('')
const updateBody = async(val) => {
        await setText(val)
        update()
}

Answer

furkan dogu picture furkan dogu · Jun 14, 2020

First of all, setText function does not return a promise that you can await and make sure the data is set.

If you want to set the state and make sure you are calling the update function after the value is set, you need to use another hook called useEffect. By using useEffect you can basically get the latest state when it is updated.

If you don't care about whether the state is set or not you can convert your async function to the following,

const updateBody = (val) => {
    setTitle(val)
    update()
}