This is my handleSearch function and i am checking if inputvalue is empty it shouldn't go further and hit my getSearch call, but sometimes if i backspace inputvalue quickly it console.logs(empty) as expected and instead of stopping it goes further n hits getSearch call below.
How to make it work correctly if inputvalue is empty.
const handleSearch = async (value) => {
setSearchTerm(value);
if (value.length <= 0 || value === "") {
console.log("empty");
setSearchResult([]);
return;
}
console.log("value", value);
const searchRes = await getSearch(value, 0);
console.log("searchRes", searchRes);
setSearchResult(searchRes);
};
CodePudding user response:
Your function does not call getSearch when the value is empty string, but it calls search before that (with previous value), and you get async result after. You have a couple of options to prevent this:
- You can do the search on button click, not on input change
- You can implement debounce for your requests (so the request only goes to server when user stopped writing)
First is easier, second is better for learning
CodePudding user response:
I simulated your situation in the codepen, because you use async method, when you type too fast, the first few async functions are still queued.
The best way is to use debounce
, it can also improve the performance of your application. Please refer here. You can download
react-use directly and use it.