I'm going out of my mind with this one. I have a react class that has some methods like this:
handleSubmit = (e) => {
this.setState({
isLoading: true,
}, this.doSearch());
}
changePage = (e) => {
this.setState({
searchPage: e,
isLoading: true
}, this.doSearch());
}
I use handleSubmit
when the user clicks submit on the search form in this component's render.
<button type="button" id="btn-search" onClick={event => this.handleSubmit(event)}>Search</button>
This works out fine, it submits, sets the state and then calls this.doSearch after it sets isLoading: true
.
Once I get the search results, I call a child component to display the result list, and I give it a handler for when the user clicks on pagination:
<ResultList searchResult={searchResult} changePage={this.changePage} />
From within the child, there is just a simple span with an onClick:
<span onClick={event => props.changePage(props.searchResult.page + 1)}>>></span>
So when the user clicks on the next page ... pager, the handler is called. I can log out e
and see the number has incremented. I then call setState and tell it to use the parent class's doSearch()
after the state has been updated. Rather, that is my goal. But it keeps running doSearch()
before the state has updated. But I know at some point the state finishes updating because by the time the component re-renders, the state has the updated searchPage
.
The only way I seem to be able to get it to run my callback AFTER the state is done updating is to wrap it in an arrow function, so that it looks like so:
changePage = (e) => {
this.setState({
searchPage: e,
isLoading: true
}, () => {
this.doSearch()
});
}
This is only an issue with changePage
which is passed to the child component and then called from there with the intention of incrementing or decrementing searchPage
. Calling this.doSearch()
from the submit handler is fine.
I get the feeling I'm not understanding scoping or this.state or instances or something....