0

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 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sadly for me the page reloads on submit irrespective of the form is valid or not. Have added the onSubmit handler snippet in the question.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.