CodexBloom - Programming Q&A Platform

Next.js: Form Validation with Zod scenarios to Reflect Updated State After Async Submission

👀 Views: 42 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
next.js react-hook-form zod form-validation JavaScript

I'm refactoring my project and After trying multiple solutions online, I still can't figure this out. I'm sure I'm missing something obvious here, but I'm stuck on something that should probably be simple. I'm working on a Next.js application (version 12.1.0) where I'm using Zod for form validation with React Hook Form. The question arises when I submit the form asynchronously, and I need the form state to reflect the changes based on the server response. After submitting the form, even though the server indicates success, the updated data isn't being picked up by the form state properly. Here's the relevant code snippet: ```javascript import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; const schema = z.object({ name: z.string().min(1, 'Name is required'), email: z.string().email('Invalid email'), }); const MyForm = () => { const { register, handleSubmit, setValue, reset, formState: { errors } } = useForm({ resolver: zodResolver(schema), }); const onSubmit = async (data) => { const response = await fetch('/api/submit', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', }, }); const result = await response.json(); if (response.ok) { reset(); // I expected the form to clear, but it still shows previous values setValue('name', result.name); // This doesn't seem to update the UI } else { // Handle behavior console.behavior(result.message); } }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input type='text' {...register('name')} /> <p>{errors.name?.message}</p> <input type='email' {...register('email')} /> <p>{errors.email?.message}</p> <button type='submit'>Submit</button> </form> ); }; ``` Despite calling `setValue` after a successful response, the UI doesn't reflect the updated state. I also tried using `reset` to clear the form, but the previous values seem to remain visible, leading to confusion. The console doesn't show any errors, and I expected the form to clear and show the new values fetched from the server. Has anyone encountered this scenario or can suggest a workaround? Any insights would be greatly appreciated! This is part of a larger API I'm building. Any ideas what could be causing this? I've been using Javascript for about a year now. Any suggestions would be helpful. What's the best practice here? Is this even possible?