State saved, but saying its not

- 1 answer

Ad

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"?

Ad

Answer

Ad

From the documentation at https://facebook.github.io/react/docs/component-api.html :

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.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.

Ad
source: stackoverflow.com
Ad