Skip to content
Advertisement

React hook form method – setValue – doesn’t work

I have some clearable select, and I want to reset the applets field in state to an empty array.

const defaultFormValues = { device: { ...initialDevice }, applets: [] };
  const { control, getValues, setValue, reset, handleSubmit } = useForm<CreateDeviceFormData>({
    mode: "all",
    reValidateMode: "onChange",
    defaultValues: defaultFormValues,
    resolver: yupResolver(validationSchema),
  });

  const onChangeHandler = React.useCallback(
    (value: Experience | null) => {
      if (value) {
        setValue("applets", getApplets(value));
      } else {
        setValue("applets", []);
        // reset(defaultFormValues);
      }

      setValue("device.experience_id", value ? value.id : undefined);
    },
    [templateSelector, setValue],
  );

  console.log("current data", getValues(), control);
  return (
    <>
      <SomeAutocompleteComponent control={control} onChange={onChangeHandler} />
      <SelectAppletsComponent control={control} />
    </>
  );


export const SelectAppletsComponent = ({ control, onChange }) => {
  const applets = useWatch({ control, name: "applets" }) as Applet[];
  const device = useWatch({ control, name: "device" }) as Device;

  if (!applets.length) {
    return null;
  }

  return (
    <SpanWrapper className="p-col-8">
      {applets.map((applet) => (
        <LabelRadio
          key={applet.id}
          inputId={applet.applet_type}
          value={applet.applet_type}
          label={applet.name}
          checked={device.applet_type === applet.applet_type}
          onChange={onChange}
        />
      ))}
    </SpanWrapper>
  );
};

the problem is that clearing the selection on UI with setValue("applets", []); not working for some reason, and I don’t understand why, and how to do it without reset method, which resets the whole state, not just single property as I understand

Advertisement

Answer

You should always register fields if you want to use them as RHF’s form state.

  React.useEffect(() => {
    register("applets");
  }, [register]);

This fixes an issue.

Update: Also a new method resetField is available

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement