'Handling with event input and debounce function

I'm trying to use this debounce function, in order to get a text inputted from user. Without debounce function, this works well (with the problem of triggering on every inputted char). When I tried to use my onChange function inside debounce, it doesn't work. After some research, I realized react was cleaning event data, so I putted event.persist() function, which removes the synthetic event from the pool and allows references to the event to be retained by user code.

With this function, when I printed event on console, I could see event data. But I can't write a code that could pass this event to onChange function, inside debounce.

My function trigged by input:

const handleOnChange = (onChange) => (e) => {
  e.persist();
  console.log(e.target);
  debounce(onChange, 500);
};

On input function, I have something like this:

<TextValidator
   name="password"
   value={password}
   onChange={handleOnChange(onChange)}
/>

I have a feeling that it's some fool error, but I'm in it for hours ago, with no success to discover where the problem is. Am I missing something?



Solution 1:[1]

debounce function return a function, but does not execute it yet. So you could think like this.

const handleOnChange = (onChange) => (e) => {
  e.persist();
  console.log(e.target);
  debounce(onChange, 500)();
};

This won't work, because each time you call handleOnChange, a new debounce function will be created. You must save debounce function some where and reuse it

const debouncedOnChange = debounce((func) => {
  fucn();
}, 500);

const handleOnChange = (onChange) => (e) => {
  console.log(e.target);
  e.persist();
  debouncedOnChange(onChange);
};

You could pass arguments like this

const debouncedOnChange = debounce((func) => {
  func();
}, 500);

const handleOnChange = (onChange) => (e) => {
  console.log(e.target);
  e.persist();
  debouncedOnChange(() => onChange(e));
};

If you use react <=16, be careful with Event pooling.

Runable solution at https://codesandbox.io/s/peaceful-margulis-mc8stj

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChickenLoveBug