1

I've experimented some cases in which calling this.setState({ foo: true }) and immediately checking this.state.foo does not return the new value true.

I can't tell now the exact case in which this happens (maybe when calling multiple times to setState() in the same iteration, I don't know). So I wonder:

Does reactjs guarantee that the following will always work?

this.setState({ foo: true });

console.log(this.state.foo);
// => prints true
2

2 Answers 2

5

Does reactjs guarantee that the following will always work?

No, setState is asynchronous method., if you want to get updated state you should use callback as second argument

this.setState({ foo: true }, () => {
  console.log(this.state.foo);
});
Sign up to request clarification or add additional context in comments.

Comments

0

It's done asynchronously. So you may not see the update within the method. Check that in componentDidUpdate. or you can see the result in the setState callback , like this :

this.setState({name: nextProps.site.name} , ()=>{

console.log(this.state.name);

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.