ProNextJS / forms-management-yt

Code for the Forms Management video on YouTube
57 stars 6 forks source link

Using form html ref can lead to unsync form #5

Open jmunozz opened 3 months ago

jmunozz commented 3 months ago

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);
        }}
      >
diwakersurya commented 1 month ago

This is correct. I spent a lot of time tracking the issue why my formdata received on server was always empty object. This fixed the issue. Thanks @jmunozz

jmunozz commented 1 month ago

Hello @diwakersurya Beware. My solution ends up not using the formRef. The action is simply call in the onSubmit callback, not through the action attribute. This does not change a lot, except... There is one downside to that: Some hooks that follows the status of the form through the action attribute are not working: https://fr.react.dev/reference/react-dom/hooks/useFormStatus