after adding lodash debounce react (onchange event.target.value dont working )

Viewed 316

I want to call api request 2 seconds after clicking on the last digit. I wanted to add lodash debounce and after that I can't write value in the input. event target value does not work after adding debounce , please tell me what I wrote wrong.

 const handleChange = (event, onChange) => {
            try {
              const response = searchContractorsById(event.target.value);
              const { address, inn, orgName, ogrn, kpp, okpo, okved } = response;
              toast.success('Найдена организация по введенному ИНН.');
            } catch (error) {
              toast.error('По введенному ИНН не найдено ни одной организации.');
            }
        
            onChange(event);
          };
            
             <Controller
                    name="inn"
                    control={control}
                    render={({ field: { value, onChange } }) => (
                    <TextField
                    value={value}
                    onChange={debounce((e) => handleChange(e, onChange), 2000)}
                    type="number"
                    />
                  )}
              />
1 Answers

since debouce is recreated on each re-render it will not save the same function instance so the solution is to memo the debounce function using useMemo. here's the solution:

 const debounceChange = useMemo(() => debounce((e) => handleChange(e, onChange), 2000), [onChange,handleChange]);

your controller now :

<Controller
                    name="inn"
                    control={control}
                    render={({ field: { value, onChange } }) => (
                    <TextField
                    value={value}
                    onChange={debounceChange}
                    type="number"
                    />

make sure useMemo dependencies(onChange,handleChange) doesn't change on each render to not cause recreation of debounceChange function

Related