Chaitu Chaitu - 20 days ago 6
Javascript Question

Will react setState immedietly set the state?

I am trying to store a value using setState, however I am setting the state and in next line I am trying to console.log it, I am not able to see the value in the console.



getInitialState: function(){
return{
myCountry: ""
}
}


var country = event.target.value;
this.setState({"myCountry": country});
console.log(this.state.myCountry); //prints nothing
console.log(event.target.value);





When I surfed for this I saw that setState is asynchronous, but I am not able to understand.

Ved Ved
Answer

You will not get the updated value of state just after calling setState(). This is because as soon as setState() is called view is re-rendered. So it is better to check the updated value inside render or add callback function to setState.
Example:

this.setState({"myCountry": country},function(){console.log(this.state.myCountry)});

Or,

render: function() {
    console.log(this.state.myCountry)
}
Comments