1

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?

3 Answers 3

2

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) );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, and for the advice about event.target too!
2

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);
    });
}

Comments

2

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} />

        // ...
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.