State saved, but saying its not
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
}
For some reason, when I check it out in React developer tools, it shows that this.state.name IS being set to the new value, but when I console.log like shown it still shows the first value instead of "Hello World"?
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM