I have a react app similar to the default ReactJS tutorial.
I have a function in a component called after a form is submitted that looks like:
getInitialState: function () {
return {
name: "First Product",
showOwner: true
}
},
handleFormSubmit: function (name) {
console.log(name); //Returns "Hello world"
console.log(this.state.name); // Returns "First Product"
this.setState({name: name});
this.setState({showOwner: false});
console.log(this.state.name); // Returns "First Product" still
}
From the documentation at https://facebook.github.io/react/docs/component-api.html :
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value.There is no guarantee of synchronous operation of calls to
setState
and calls may be batched for performance gains.
Also:
The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.
So, following the documentation, you would want this from your code:
handleFormSubmit: function (name) {
console.log(name); //Returns "Hello world"
console.log(this.state.name); // Returns "First Product"
this.setState({
name: name,
showOwner: false
}, function() {
// Should return "Hello world" after the state has been set.
console.log(this.state.name);
}.bind(this));
// Returns "First Product" still, since setState is not synchronous
console.log(this.state.name);
}
I don't know react, but that's what the docs say and I have no reason to believe that wouldn't work.