Skip to content

Using form html ref can lead to unsync form #5

@jmunozz

Description

@jmunozz

Hi
Thanks for your work !
I noticed that the from html object can be unsync with the react-hook-form object.
In my case I use a form field that is passed to the form as a default value but cannot be modified by the user.

  const form = useForm({
    defaultValues: { "someIHiddenId": "1" , "userField1": "", "userField2": ""} ,
    resolver: zodResolver(...),
  });

Then I render 2 form fields

              <FormField
              control={form.control}
              name="userField1"
              render={({ field }) => (
                    <FormItem>
                      <FormLabel>Field 1</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
              )}
            />

When submitting the form. The html form has no knowledge of the "someIHiddenId" field.
This part fails:

     <form
       ref={formRef}
       action={formAction}
       onSubmit={(e) => {
         e.preventDefault();
         form.handleSubmit(() => {
           formAction(new FormData(formRef.current!));
         })(e);
       }}
     >

Instead I rather use the value returned by form.handleSubmit (an object) and convert it to formData.

      <form
       ref={formRef}
       action={formAction}
       onSubmit={(e) => {
         e.preventDefault();
         form.handleSubmit((clientValidatedData) => {
           formAction(objectToFormData(clientValidatedData));
         })(e);
       }}
     >

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions