48

Here I try to set state.autocomplete to 'hello' and then print it, but state seems to be null. How can that be when I just updated the state using setState? data is set as a global variable.

  var data = {
    populate_at: ['web_start', 'web_end'],
    autocomplete_from: ['customer_name', 'customer_address']
  };


  var AutocompleteFromCheckboxes = React.createClass({
    handleChange: function(e) {
      this.setState( { autocomplete_from: 'event.target.value' } );
      console.log('autocompleteFrom state: ', this.state.autocomplete_from);
      // ^  => Uncaught TypeError: Cannot read property 'autocomplete_from' of null
      return 1;
    },
    render: function() {
      var autocompleteFrom = this.props.autocomplete_from.map(function(value) {
        return (
          <label for={value}>
            <input type="checkbox" name={value} value="{value}"
              onChange={this.handleChange.bind(this)}
              ref="autocomplete-from"/>
            {value}
          </label>
        );
      }, this);
      return (
        <div className="autocomplete-from">
          {autocompleteFrom}
        </div>
      );
    }
  });

  var DynamicForm = React.createClass({
    getInitialState: function() {
      return {
        name              : null,
        populate_at       : null,
        same_as           : null,
        autocomplete_from : "not set",
        title             : null
      };
    },
    saveAndContinue: function(e) {
      e.preventDefault();
      var data = {
        name     : this.refs.name.getDOMNode().value,
      };
      console.log('data: ' + data.name);
    },

    render: function() {
      return (
          <AutocompleteFromCheckboxes
            autocomplete_from={this.props.data.autocomplete_from} />
      );
    }
  });


  var mountpoint = document.getElementById('dynamic-form');
  if ( mountpoint ) {
    React.render(<DynamicForm data={data} />, mountpoint);
  }

});
2
  • @zvona, adding .bind(this) caused this warning Warning: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See AutocompleteFromCheckboxes dynamic-form.js?body=1:13 populateAtCheckbox
    – martins
    Commented Apr 7, 2015 at 11:39
  • Yes, I noticed that. My mistake :/. Commented Apr 7, 2015 at 11:41

3 Answers 3

119

From the reactjs docs:

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.

https://facebook.github.io/react/docs/component-api.html

What you can do is pass a callback function to setState which is triggered once the state has been updated:

this.setState(
    {autocomplete_from: ...}, 
    function () {
        ... at this point the state of the component is set ...
    }
)
7
2

You need to set the initial state of your component, try adding the following to the top of your component.

getInitialState: function() {
  return {
   autocomplete_from: ''
  };
}

EDIT:

In your DynamicFrom component you have:

render: function() {
  return (
      <AutocompleteFromCheckboxes
        autocomplete_from={this.props.data.autocomplete_from} />
  );
}

Since you are trying to reference the state you should write

autocomplete_form={this.state.autocomplete_from}

Also you are trying to set the state from a child component and it should not directly modify state. The best way to approach this is to pass down a function from DynamicFrom(holds the state) to AutocompleteFromCheckboxes. Like so.

var DynamicForm = React.createClass({
    handleChange: function(value) {
       this.setState({autocompelete_from: value});
    },
    render: function() {
       return(
          <AutocompleteFromCheckboxes 
            autocomplete_from={this.state.autocomplete_from}
            handleChange={this.handleChange} 
          />
       );
    },
    ....
});

Then call that function in your child component

AutocompleteFromCheckboxes = React.createClass({
    ....
    onChange={this.handleChange}
    ....
    handleChange: function(e) {
     this.props.handleChange(e.target.value);
    }
});
1
  • Sorry, I didn't include getInitialState in my original post. Updated the post to include more code now.
    – martins
    Commented Apr 7, 2015 at 11:53
2

To see updated state value after doing setState you should do something like below

 this.setState( { autocomplete_from: 'event.target.value' }, () => { 
    console.log(this.state.autocomplete_from);//this will print the updated state value
 });

Not the answer you're looking for? Browse other questions tagged or ask your own question.