How to use Redux Saga debounce but fetch first instead of waiting for n milliseconds

Viewed 401

Is there a way in redux-saga to only fetch one time during for example in 5 seconds?

I know that there's debounce function:

yield debounce(5000, 'SAMPLE_ACTION', actionToFetchFirst)

but what I want is for it to fetch first rather than waiting for 5 seconds for initial fetch

2 Answers

I want is for it to fetch first rather than waiting for 5 seconds for initial fetch

You can specify leading=true in lodash.debounce options:

lodash.debounce(func, [wait=0], [options={}])

[options.leading=false] (boolean): Specify invoking on the leading edge of the timeout.

lodash.debounce(5000, 'SAMPLE_ACTION', { leading: true });

Or just add a condition, something like:

if (input.length > 1) fetchDebounced();
else fetch();

If I understood correctly what you are looking for is called throttle meaning that in the timespan of 5 seconds this action will only be called once, if so you can use lodash throttle func for this https://lodash.com/docs/4.17.15#throttle

Related