React Hook Form: useForm not returning any errors in formState

2.1k views Asked by At

I am creating a app using T3 stack + react-hook-form + zodResolver:@hookform/resolvers/zod

I have a zod schema defined as below

export const AccountSchema = z.object({
  id: z.string().uuid().optional(),
  title: z.string().min(1, { message: 'Title is required' }),
  description: z.string().min(1, { message: 'Description is required' }),
});

export type Account = z.infer<typeof AccountSchema>;

And in a component I am making use of useForm Hook as below

const editForm = useForm<Account>({ resolver: async (val, ctx, opt) => {
    const res = await zodResolver(AccountSchema)(val, ctx, opt);
    console.log('Validation Result: ', res, val);
    return zodResolver(AccountSchema)(val, ctx, opt);
  }});

form Submit Handler:

onSubmit={void editForm.handleSubmit(() => console.log('success'), (val) => console.log('Errors: ', val))}

Packages used:

"zod" -> "3.20.7"
"@hookform/resolvers" -> "2.9.11"
"react-hook-form" -> "7.43.5"

Issue: Looking at the console log, I can see zodResolver is passing correct errors to useForm resolver but in the formState object errors is always undefined ie: editForm.formState.errors.title is always returning as undefined. Also on submit always reloads the page irrespective of the form being valid or invalid.

2

There are 2 answers

0
Parshuram On BEST ANSWER

Wow. The "void" before handleSubmit was causing the issue. Had added void due to eslint@typescript-eslint/no-misused-promises rule.

1
TDEgypt On

Well, it just happened to me and turned out that I'm calling the wrong onSubmit action in the form field:

const schema = z.object({
  description: z.string().min(3).max(50).nonempty(),
  amount: z.number().min(0).nonnegative(),
  category: z.enum(categories),
});    

type FormData = z.infer<typeof schema>;
    
    const DataForm = () => {
      const {
        register,
        handleSubmit,
        formState: { errors },
      } = useForm<FormData>({ resolver: zodResolver(schema) });

Then, changing the form onSubmit solved the issue:

<form onSubmit={handleSubmit()}>

Hope this helps out.