Reputation: 4998
I've a button and I'm calling an arrow function contentLoad on click of that button. I've two objects. One is 'obj' and other is 'content' which is a mere copy of 'obj'.
this.setState({content: obj})
When i print both of them on console. The other one i.e the copied one is null for the first click. However everything looks good after the first click.
The entire project is here
And the js code is this
Upvotes: 2
Views: 740
Reputation: 989
setState is asynchronous, so it probably did not complete before the console.log which immediately follows it.
setState allows a callback function to be passed which will be invoked after the state has been modified. Try this with a callback instead:
this.setState({content: obj}, () => console.log(this.state.content));
Upvotes: 3
Reputation: 883
A lesser known fact is that this.setState
is an asyncronous function in React.
It takes a second parameter which is a callback to to execute once the state is actually set.
this.setState(new_state, optional_callback_function)
So, when you see null
being printed when logging content
, it is because the state has not been set before calling the console.log
and you simply see the initial value, null
.
To remedy this and see the correct value everytime, you could refactor your code like so:
this.setState({content: obj}, () => {
console.log(this.state.content);
})
Upvotes: 3
Reputation: 1130
According to manual here:
"Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details)."
Upvotes: 3