Reputation: 1549
I am using lodash throttle like this
const throttledFetch = _.throttle(fetch, 10000, { 'leading': false });
I need to trigger this upon a certain notification event I am getting from a ws. So the idea was, if I get 10 notifications at almost the same time, to have the fetch
function fire only once at the wait of 10 seconds.
Instead, what is happening is that the fetch functions gets fired 10 times after the 10 second delay.
How can I fix this? I could use any other methods.
Any suggestion is welcome
Upvotes: 2
Views: 1611
Reputation: 962
The throttled function should remain the same between re-renderings, meaning we have to use React's UseCallback function. This would have worked if you changed:
const throttledFetch = _.throttle(fetch, 10000, { 'leading': false });
To
const throttledFetch = useCallback(_.throttle(fetch, 10000, { 'leading': false }), []);
Upvotes: 2
Reputation: 355
if we are going to call the fetch
function only once, for all the N requests at same time, we should be using debounce
instead of throttle
. That is the best way to respond to user interaction / some event from the Web socket listener.
The response should be faster, and also it should not be called frequently. In order to full fill the above requirement, I would be going with _debounce
.
As answered by Tuxedo Joe
in the above answer, we can go with useCallback
approach, since the reference is going to stay the same between re-renders.
const asyncFetch = useCallback(_.debounce(fetch, 10000, { 'leading': false }));
Upvotes: 0
Reputation: 14
Keep a counter for the invocation and check it for invoking only once.
Upvotes: 0