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
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);
})
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)."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With