Having some trouble with the async nature of setState()

Hello,

I am working on the React Calculator project, and I am having some trouble with the asynchronous nature of this.setState().

Here is my code:

if (event.target.id === 'equals') {
  //when '=' is pressed, the screen and value are updated
  this.setState({ 
    screen: eval(this.state.screen),
    value: eval(this.state.screen)
  })
  //if the value displayed on the screen contains a '.', and if 
  //there are more than 4 decimal places, then round the value
  setTimeout(() => {
    if (String(this.state.screen).includes('.')) {
      let decPlaces = String(this.state.screen).length - String(this.state.screen).indexOf('.');
      if (decPlaces > 4) {
        this.setState({ screen: this.state.screen.toFixed(4) });
      }
    }
  }, 0)
  return; 
}

The problem is, when I use if (this.state.screen.includes('.')) without setTimeout(), then it would always access the previous, non-updated value of the screen state. I am guessing this is because setState() is asynchronous.

This method using setTimeout() technically works, but if I try to calculate something like 2 / 3, the display will show 0.6666666666666 for a split second before rounding it to 0.667.

And if I don’t use setTimeout(), then my if statement that checks for a decimal will return false, as it won’t have received the updated state values.

Could someone point me in the right direction as to how I could address this issue?

Thank you.

Okay I’m going to try setting the value to a variable and rounding any decimal places BEFORE calling this.setState(). That should work. I think. I hope.

If you access the state functionally you will get the most updated version of the state i had the same problem when i did that project.

this.setState(state =>({
num1: […state.num1, x]

The only other place you are able to get the current state is in the render

1 Like

@cmar

Thank you for that advice!

Also the class based react that is taught here is mostly obsolete if you really want to learn react find a modern course that teaches react with hooks. I did the course but am going to do another more modern course that teaches the current version of react.

1 Like

@cmar

Yeah I hear everyone talking about hooks, but FCC doesn’t teach them.

Do you have any recommendations as to where I can learn modern React?

@cmar

I bookmarked this page a while back https://react-tutorial.app/ but only the first 9 chapters are free, and the rest are paid.

Im still looking into it i am still working on some backend development here then im going to look into it more.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.