首页 > 解决方案 > 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?

标签: reactjsreact-hook-formdebounce

解决方案


这可以通过以下实现来实现;

<Controller
   name={fieldName}
   rules={{ required: `errors.${fieldName}.required` }}
   render={({ field, fieldState: { error } }) => (
      <input
         type="text"
         error={error && t(`${error.message}`)}
         onChange={debounce((e) => field.onChange(e), 50)}
         defaultValue={field.value}
       />
    )}
  />
    

推荐阅读