Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - State not updated

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);   }  }); 
like image 658
martins Avatar asked Apr 07 '15 11:04

martins


People also ask

Why state is not updating in React JS?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

How do I update my React state?

Create another method inside the class and update the state of the component using 'this. setState()' method. Pass the state object in a JSX element and call the method to update the state on a specific event like button click.

Why setState is not updating immediately?

setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.

How wait for state to update React?

Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.


1 Answers

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 ...     } ) 
like image 58
Anthony Blackshaw Avatar answered Oct 03 '22 14:10

Anthony Blackshaw