M
M
Mesuti2022-02-08 01:40:43
React
Mesuti, 2022-02-08 01:40:43

Why might debounce not work?

Hey!
Why does it work without delay?

function debounce(fn, ms) {
    let timeout;
    return function () {
      const fnCall = () => {
        fn.apply(this, arguments);
      };
      clearTimeout(timeout);
      timeout = setTimeout(fnCall, ms);
    };
  }

  useEffect(() => {
    debounce(getData(), 2000);
  }, [state.query]);

  function getData() {
...

https://stackblitz.com/edit/react-dadata-yf32o2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-02-08
@Mesuti

debounce(getData(), 2000);

That is, for at least four and a half years of programming, you have not learned to distinguish between the function itself and its call. Well, just wave your hand, the case is hopeless.
In addition, the debounced function must be the same every time the component is rendered, so we wrap it in useCallback , and in order for it to use the current state, we will pass it as a parameter:
const getData = useCallback(debounce(query => {
  /*
   * здесь всё по-старому, кроме body: JSON.stringify({ query: state.query }),
   * надо заменить на body: JSON.stringify({ query }),
   */
}, 2000), []);

useEffect(() => {
  getData(state.query);
}, [ state.query ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question