0

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.

Thuan Nguyen
  • 876
  • 3
  • 16
  • 32

2 Answers2

2

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(() => {
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66