0

This.setState() is working for almost all variables in my component, but not all.

When i try to set the state of a state variable the value does not change which is a very strange behavior.

 this.setState({ notSaved: size }, () => {

            console.log(this.state.notSaved, 'notSaved','size',size);
          }); 
    }

Code Result of the console.log

enter image description here

This is not a problem with the async behavior of the setSate, as you can see in the image below, because even if I console.log the value inside the callback, still unchanged. So this is not a duplicated question.

enter image description here

  • Can you please put the complete code of your component? And you should know that setState Method is async. So code your component keeping that in mind. Your are setting not saved value twice one by one, react will not guarantee the execution order for this. – Piyush N Sep 06 '19 at 17:12
  • Possible duplicate of [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Rikin Sep 06 '19 at 17:12
  • The problem is that the value is never updated. I'm aware that setState is async but the value in the variable notSaved never changes no matter what I wait/do. – Carlos Gonçalves Sep 06 '19 at 18:10

1 Answers1

0

setState(updater[, callback])

use callback in setState to read new value. setState is async and you are expecting your state to be updated instantly. To make sure your state got updated, you would have to leverage on call back function passed in as second argument.

      this.setState((state, props) => {
        return { notSaved: size }
      }, () => console.log(this.state.notSaved, 'updated notSaved')); 

Detailed explanation by Dan on why is setState asynchronous?: https://github.com/facebook/react/issues/11527#issuecomment-360199710

Rikin
  • 5,351
  • 2
  • 15
  • 22