Reputation: 886
I'm handling search feature onChange using Axios. It works fine.
But the problem is when the user deletes input to empty. The request still sent.
My code.
handleSearch = (e) => {
const query = e.target.value;
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
if (query === '') // do something ????
requestApi.searchMultiData('search/multi', query)
.then(response => {
this.props.data(response.data);
})
.catch(error => console.log(error));
}, 300);
};
How can I handle that? My solution is when text input empty. The request should be canceled. Any ideas for working with that? Tks.
Upvotes: 0
Views: 562
Reputation: 178079
Looking at this again, I suggest this:
handleSearch = (e) => {
const query = e.target.value;
if (this.timeout) clearTimeout(this.timeout);
if (query.trim() === '') return; // here is the logical place to leave
this.timeout = setTimeout(() => {
Upvotes: 2
Reputation: 14928
You are looking for a way to early exit from function. It means that a part or most of the code in your callback function will not be executed if a condition is met (query
is empty: see how to implement it here).
I'd also recommend using trim()
to remove the whitespace; otherwise, values like will be considered correct, which they are probably not.
Upvotes: 0