Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting null object on console for the first run in reactjs

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

like image 936
Tanzeel Avatar asked Mar 21 '26 21:03

Tanzeel


2 Answers

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);
})
like image 98
SerShubham Avatar answered Mar 24 '26 10:03

SerShubham


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)."

like image 44
Wolfetto Avatar answered Mar 24 '26 11:03

Wolfetto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!