ReactJS function isn't getting latest state
reactjs
Solution
`setState` takes a callback which allows you to ensure `this.loadGroupsFromQuery()` is called only after `this.state` is updated.
this.setState({...}, function() {
this.loadGroupsFromQuery();
});
Problem
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> ) } }) ```