0
votes

I'm having some issues with react-hook-form where after unregistering a field and keeping its current value, my form won't submit since all fields are validated when attempting to submit it.

My simplified user case is that my form has two field firstname and lastname with a buttom that will unregister/register lastname and another to submit the form. Please check the following codesanbox.

To reproduce the issue, click 'unregister lastName' than 'submit'.

Current result: Even thought lastName was unregistered, form isn't submitted since lastName has invalid values (was registered previously with required: true).

Expected resut: Form should be submited with: { firstName: "", lastName: "" }

My project has the following packages/versions: react (~16.13.1), react-dom (~16.13.1), react-hook-form (^7.2.2), react-scripts (~3.4.1)

1

1 Answers

1
votes

with v7 you need to set

shouldUnregister: true //<== NEW
  const { register, unregister, handleSubmit, formState, getValues } = useForm({
    mode: "onChange",
    defaultValues: {
      firstName: "Random",
      lastName: "Name"
    },
    shouldUnregister: true
  });

See documentation: https://react-hook-form.com/api/useform