Home > Enterprise >  Lodash Debounce sends request without callback React JS
Lodash Debounce sends request without callback React JS

Time:10-27

I'm having problems with setting up lodash debounce in the function to make an API request. For some reason callback doesn't happen and the value sends every time I type.


import debounce from "lodash/debounce";

  const handleChange = (event) => {
    const { value: nextValue } = event.target;
    const debouncedSave = debounce((nextValue) => dispatch(movieActions.getMovies(nextValue), 1000));
    debouncedSave(nextValue);
  };
  

I'm using material ui and have this in return:

<Autocomplete
  onInputChange={handleChange}
/>

CodePudding user response:

Your debounced function is created multiple times for each change event and that causes the problem. I will use a simplified example with a simple input and a console.log instead of your dispatch, but you can apply the solution to your case as well.

The simplest solution would be to move the debouncedSave declaration outside your component.

const debouncedSave = debounce((nextValue) => console.log(nextValue), 1000);

export default function App() {
  const handleChange = (e) => {
    const { value } = e.target;
    debouncedSave(value);
  };

  return <input onChange={handleChange} />;
}

or else if you want to keep the debounced function declaration inside your component you can use a ref, to create and use the same instance each time, no matter the re-renders:

export default function App() {
  const debouncedSaveRef = useRef(
    debounce((nextValue) => console.log(nextValue), 1000)
  );

  const handleChange = (e) => {
    const { value } = e.target;
    debouncedSaveRef.current(value);
  };

  return <input onChange={handleChange} />;
}
  • Related