简体   繁体   English

如何在 React 中使用 lodash 限制这个 api 请求

[英]How to throttle this api request using lodash in React

I am using React and trying to figure out how to implement the lodash debounce method to throttle the api request.我正在使用 React 并试图弄清楚如何实现 lodash debounce 方法来限制 api 请求。 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.它应该等待大约 3 秒,然后再根据amountValue调用 api 方法,这基本上是一个 state 值。 Here is my code which I am trying to throttle the api request.这是我试图限制 api 请求的代码。

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.如果您使用 lodash 进行去抖动,则必须使用 useCallback 挂钩创建 function 的去抖动版本。 If your are using it in Input field, please provide the debounced function inside handleChange.如果您在 Input 字段中使用它,请在 handleChange 中提供去抖 function。

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();
    }
  }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM