Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS function isn't getting latest state

Tags:

reactjs

I'm trying out ReactJS, but am running into difficulty incorporating it into my form. I'm building out an auto-suggest form in ReactJS. In my onChangeQuery, I'm setting the state and then calling out to an AJAX function to grab suggestions from my server-side code; however, I've noticed that the loadGroupsFromServer function isn't getting the latest state... It's one key stroke too slow. I know setState isn't instantaneous, but then why would I ever use setState for my forms? Is it better to use refs? Better to just get the value from e.target.value?

Help!

  var GroupForm = React.createClass({     getInitialState: function() {       return {query: "", groups: []}     },     componentDidMount: function () {       this.loadGroupsFromServer();     },     loadGroupsFromServer: function () {       $.ajax({         type: "GET",         url: this.props.url,         data: {q: this.state.query},         dataType: 'json',         success: function (groups) {           this.setState({groups: groups});         }.bind(this),         error: function (xhr, status, err) {           console.error(this.props.url, status, err.toString());         }.bind(this)       });     },     onChangeQuery: function(e) {       this.setState({query: e.target.value})       this.loadGroupsFromServer();     },     render: function() {       return (         <div>           <form class="form form-horizontal">             <div class="col-lg-12">               <input type="text" className="form-control" value={this.state.query} placeholder="Search for groups" onChange={this.onChangeQuery} />             </div>           </form>           <GroupList groups={this.state.groups} />         </div>       )     }   }) 
like image 435
zilla Avatar asked Nov 27 '14 18:11

zilla


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 you force a state to update in React?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.

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.


2 Answers

setState takes a callback which allows you to ensure this.loadGroupsFromQuery() is called only after this.state is updated.

this.setState({...}, function() {   this.loadGroupsFromQuery(); }); 
like image 141
Paul O'Shannessy Avatar answered Oct 02 '22 18:10

Paul O'Shannessy


setState Best Practice

ES5

this.setState(function(state, props){    return {       query: e.target.value    } }, function()=>{    //after callback  }); 

ES6

 this.setState((state, props) => ({     query: e.target.value  }), ()=>{    //after callback   }); 
like image 44
Burak Demirezen Avatar answered Oct 02 '22 18:10

Burak Demirezen