Muhambi Muhambi - 5 years ago 111
Javascript Question

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(; // Returns "First Product"

this.setState({name: name});
this.setState({showOwner: false});

console.log(; // Returns "First Product" still

For some reason, when I check it out in React developer tools, it shows that 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 Source

From the documentation at :

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.


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(; // Returns "First Product"

    name: name,
    showOwner: false
  }, function() {
    // Should return "Hello world" after the state has been set.

  // Returns "First Product" still, since setState is not synchronous

I don't know react, but that's what the docs say and I have no reason to believe that wouldn't work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download