0

I have in my constructor set the state of key to 0 and on CommponentDidMount have the following code:

 this.setState({ key: Math.random() });      
 console.log(this.state.key)
 this.forceUpdate();
 console.log(this.state.key)

But I get the same value for state. How is that possible?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Rob Smith
  • 137
  • 1
  • 9
  • Possible duplicate of [Why calling setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) – Mayank Shukla Aug 14 '17 at 11:31

1 Answers1

0

The (setState) method is behaving like async, so any console.logs or logic after it doesn't mean it will wait till the state is updated, any logic you want to make sure it's executed after the state is updated wrap it in function and pass it as a second param to (setState) like this:

this.setState({ key: Math.random() }, () => {
    console.log(this.state.key)
});

Also note that you can force update by using the (setState) with empty object like this: this.setState({});

Anas Tawfeek
  • 109
  • 8