2

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()
}
Youssef AbouEgla
  • 1,445
  • 10
  • 21
Yogi Katba
  • 189
  • 1
  • 2
  • 6

2 Answers2

1

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()
}
furkan dogu
  • 182
  • 1
  • 13
  • ```useEffect(() => {update()}, [text])``` I did this but it is the same result. I want my update function to run after 1.5s after user stops typing. How to do that? – Yogi Katba Jun 14 '20 at 19:09
1

You can use useEffect hook to trigger a function which you want to get triggered after the state has been updated.

const [text, setText] = useState('')

useEffect(() => {
  update()
}, [text]); // This useEffect hook will only trigger whenever 'text' state changes

const updateBody = (val) => {
  setText(val)
}

Basically you useEffect() hook accepts two arguments useEffect(callback, [dependencies]);

callback is the callback function containing side-effect logic. useEffect() executes the callback function after React has committed the changes to the screen. Dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings.

Put your side-effect logic into the callback function, then use the dependencies argument to control when you want the side-effect to run

you can find more info about useEffect() hook in this article

Hadi Mir
  • 4,497
  • 2
  • 29
  • 31