Happy Friday! Im just on here because I have an issue with a stale closure that is happening in my react cryptocurrency project. I have a function storing an api call that is supposed to run upon render and every 6 seconds after. It also is supposed to take the debounced input and make a call against the same api url every 500ms after the user stops typing into the input field.
function handleInitPoll(baseAndQuote, side, value) {
getSwapPrice(baseAndQuote, side, value || 0)
.then((res) => {
if (!res.price) {
setIsLoading(true);
} else if (res.error) {
setInputErrorMessage(res.error);
} else if (res.price) {
setIsLoading(false);
setSwapPriceInfo(res);
}
});
}
As you can see, it has 3 arguments being passed into it.
And I am debouncing it in my onChangeHandler:
const debounceOnChange = useCallback(debounce(handleInitPoll, 500, pair, transactionType, fromCurrencyAmount), []);
const handleAssetAmount = (e) => {
const { value } = e.target;
const formattedAmount = handleAssetAmountFormat(value);
setFromCurrencyAmount(formattedAmount);
validateInputAmount(formattedAmount);
debounceOnChange(pair, transactionType, formattedAmount);
};
And here is the useEffect that is polling the function:
useEffect(() => {
if (pair && transactionType && symbol === baseAsset) {
handleInitPoll(pair, transactionType, fromCurrencyAmount);
}
const timer = setInterval(handleInitPoll, 6000, pair, transactionType, fromCurrencyAmount);
return () => {
clearInterval(timer);
};
}
}, [pair, transactionType, fromCurrencyAmount, symbol]);
So this actually works in that it polls with the default given values and return a response from my api. Entering an amount from the textfield with the onChange handler also populates the parameter 'fromCurrencyAmount'.
However, there is an issue where the debouncing does not work. It simply makes an api call against each and every key stroke without 500ms after I stopped typing. Literally every key stroke will trigger an api call. But if I remove the fromCurrencyAmount state variable from the useEffect dependency array, the debouncing works in that it makes a debounced call against the api in the handleInitPoll function, but the next poll that occurs, the subsequent api parameters being sent are back to defaults instead of being a continuation of the inputs.
This is something I guess is a side effect of the variables being placed into the dependency array. I know that having the fromCurrencyAmount inside the dependency array will prevent api call from passing in default parameters but it defeats the purpose of debouncing since it will make a call on every onChange event.
Are there any solutions that you know about? Any help is appreciated, thanks!