Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding debounce to react hook form

I have the following controlled component set up using react-hook-forms.

          <Controller
            control={control}
            name={"test"}
            render={({ field: { onChange, value, name } }) => (
              <Dropdown
                name={name}
                value={value}
                handleChange={onChange}
                options={foodCategories()}
              />
            )}
          />

I want to call a debounce and and I tried doing the following:

            handleChange={debounce(onChange, 500)}

but I keep getting errors throw:

This synthetic event is reused for performance reasons, Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, 

How can I call debounce on a controlled react hook form component?

like image 321
lost9123193 Avatar asked Aug 23 '26 07:08

lost9123193


1 Answers

In such situations, I use the following piece of code:

Custom input field:

const TextInput = ({ name, setValueDebounce }: { name: string; setValueDebounce: (value: string) => void }) => {
    const handleTyping = useCallback(
        debounce((value) => {
            if (setValueDebounce) setValueDebounce(value);
        }, 300),
        [],
    );

    return (
        <Controller
            name={name}
            render={({ field: { value, onChange, ...fieldProps } }) => (
                <input
                    id={name}
                    value={value || ''}
                    onChange={(e) => {
                        onChange(e.target.value);
                        handleTyping(e.target.value);
                    }}
                    {...fieldProps}
                />
            )}
        />
    );
};

Where name is the property name provided in form, and setValueDebounce is the debounce function, which triggers after 300ms delay

 <TextInput
     name="name"
     setValueDebounce={(value: string) => console.log(value)}
 />
like image 154
Kifoxive Avatar answered Aug 24 '26 22:08

Kifoxive