Reputation: 36514
I'm creating a search page component, that contains a number of inputs to filter the search results.
Each input changes the state of the component, and should trigger an AJAX call to refresh the search results:
handleSearchStringChange(event) {
this.setState({
filterSearchString: event.target.value
});
loadSearchResults(event.target.value);
}
render() {
return (
// ...
<input type="text" value={this.state.filterSearchString} onChange={this.handleSearchStringChange} />
// ...
);
}
This is all good, however, as soon as you add more filters, it becomes cumbersome to pass all the filter values to loadSearchResults()
.
What I'd like to do, is update the state of the component using setState()
as I do above, and then have loadSearchResults()
build the AJAX request from the state alone.
I can't do this right now, because setState()
is asynchronous, and doing so would make loadSearchResults()
use potentially outdated data.
Is there any way to trigger the AJAX call after setState()
has completed?
Upvotes: 1
Views: 194
Reputation: 1249
setState accepts a callback, when it finished with state update:
handleSearchStringChange(event) {
this.setState({
filterSearchString: event.target.value
}, () => {
loadSearchResults(this.state.filterSearchString);
});
}
render() {
return (
// ...
<input type="text" value={this.props.searchString} onChange={this.handleSearchStringChange} />
// ...
);
}
Upvotes: 2
Reputation: 5929
You can do like that. You can read this article who will help you with this case https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
handleSearchStringChange(event) {
this.setState({
filterSearchString: event.target.value
}, () => {
loadSearchResults(event.target.value);
});
}
Upvotes: 2
Reputation: 37594
Yes, with the callback from setState
e.g.
I would also not use event.target
in the setState call since it can be nullified. Instead store it in a local variable
let filterSearchString = event.target.value;
this.setState({ filterSearchString },
() => loadSearchResults(this.state.filterSearchString) );
Upvotes: 2