Reputation: 2421
Ok so I am stuck on what I thought would be simpler and maybe I've just been looking at the terminal too long!
I have submitted a project for the React course I am doing and in the code review an improvement was suggested by the reviewer to add an if
statement check to then
portion of a promise.
This is what the reviewer said:
Inside 'then' part of the promise check if(query === this.state.query) to ensure you are not going to replace the contents to an old response.
bookSearch(query) {
if (query.length > 0)
BooksAPI.search(query)
.then(searchResults => this.setState(currentState => ({
results: this.updateExistingShelves(searchResults)
})));
}
I have tried adding an if
in but I keep getting syntax errors. What is the correct way to do this?
I cannot add it to the initial if
in this method as it messes up the first query and nothing ever gets into the BooksAPI
call
Upvotes: 0
Views: 89
Reputation: 5669
You can add an if inside then like,
bookSearch(query) {
if (query.length > 0)
BooksAPI.search(query)
.then(searchResults => {
if(query === this.state.query){
this.setState(currentState => (
{
results: this.updateExistingShelves(searchResults)
}))
}
);
}
Upvotes: 1
Reputation: 2311
I think this is what he means:
bookSearch(query) {
if (query.length > 0)
BooksAPI.search(query)
.then(searchResults => {
if (query === this.state.query) {
this.setState({ results: this.updateExistingShelves(searchResults) });
}
});
}
Upvotes: 1