I am using React and trying to figure out how to implement the lodash debounce method to throttle the api request. I have tried to implement it based on examples on the internet but seems like it doesn't work in this case. And it is supposed to wait about 3 seconds before the api method gets called again based on the amountValue
, which is basically a state value. Here is my code which I am trying to throttle the api request.
import debounce from 'lodash/debounce';
const [amountValue, setAmountValue] = useState('');
const handleGetSwapPrice = useCallback(() => {
getFinalPrice(amountValue)
.then((res) => {
const formattedPrice = formatCurrency('USD', res.price);
if (!res.price) {
setIsLoading(true);
} else {
setIsLoading(false);
}
setSwapPrice(formattedPrice);
});
}, [baseAsset, quoteAsset, transactionType]);
useEffect(() => {
handleGetSwapPrice();
}
}, []);
If your are using lodash for debounce, you have to create a debounced version of the function using useCallback hook. If your are using it in Input field, please provide the debounced function inside handleChange.
import debounce from 'lodash/debounce';
const [amountValue, setAmountValue] = useState('');
const handleGetSwapPrice = () => {
getFinalPrice(amountValue)
.then((res) => {
const formattedPrice = formatCurrency('USD', res.price);
if (!res.price) {
setIsLoading(true);
} else {
setIsLoading(false);
}
setSwapPrice(formattedPrice);
});
}
const debouncedAPICall = useCallback(debounce((e) => handleGetSwapPrice(e), 3000), []);
useEffect(() => {
debouncedAPICall();
}
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.