Thidasa Pankaja
Thidasa Pankaja

Reputation: 1070

How to dispatch an action with delay (debounce)

I have a scenario where I need to dispatch an action two seconds after a input is completed. (Let's say a user type 1000 without an interval of 2 seconds, so I need to dispatch action only after 1000 is typed and after 2 seconds from it).

Previously I used debounce-promise to do such a thing, where I needed to get dropdown list from API, but for that I directly used the library with AJAX call in component. It worked correctly.

Now I need to dispatch an action like this.

  // should be dispatched only for the last request
  const getRateReq = dispatch(getRates());

  const getRate = debounce(getRateReq, 2000, {
    leading: false,
  });

  const onChange = (e) => {
     setValue(e.target.value);
     getRate(e.target.value);
  }

Now also the action dispatches only after two seconds of completing the typing. But then it makes all the requests for 1, 10, 100, 1000 (even though 1000 is inputted without two seconds interval). How can I get this fixed and dispatch an action only for the last input in 2 seconds ?

Any help would be appreciated. Thanks

EDIT : Added the basic onChange function

Upvotes: 3

Views: 2724

Answers (3)

kyorilys
kyorilys

Reputation: 832

   <input onChange={_.debounce((e)=> dispatch(search(e.target.value)), 300)} />

Can do something like this and remember to import the lodash and dispatch

Upvotes: 0

Saqib Naseeb
Saqib Naseeb

Reputation: 741

you can do something like this.

let timeOut = null;
SearchFilter: (name, value) => {
    clearTimeout(timeOut);
    dispatch(SearchFilter(name, value));
    timeOut = setTimeout(() => {
            dispatch(callfunction());
        }, 2000);
    }

it will dispatch the action waiting 2 second for the input.

Upvotes: 5

MubashirEbad
MubashirEbad

Reputation: 289

You need to use the debounce method of loadash and do something like:

onChange = debounce(anyInput => {
    }, 2000);

so you have to make your API call within the onchange method when you finished typing and 2 seconds after that. Not sure this is what you are asking?

Upvotes: 1

Related Questions