React Hook Form: Values reset when navigating steps (multi-step form) #13386
Replies: 3 comments 5 replies
-
|
One thing in the posted code is expected: useEffect(() => {
if (method === "ONLINE") {
form.setValue("venue", "");
}
if (method === "PHYSICAL") {
form.setValue("platform", undefined);
}
}, [method, form]);With the default For async function handleNext() {
console.log("before", form.getValues());
const isValid = await form.trigger(steps[currentStep].fields);
console.log("after trigger", form.getValues());
if (isValid && !isLastStep) {
setCurrentStep((prev) => prev + 1);
queueMicrotask(() => console.log("after step", form.getValues()));
}
}If the values disappear only after the step changes, replace one custom field with a plain registered input temporarily: <input {...form.register("title")} />If the plain input keeps its value, the issue is in the custom field wiring. If it also resets, check whether the whole |
Beta Was this translation helpful? Give feedback.
-
|
@zixuanng8368-sudo I would suggest you to try this. |
Beta Was this translation helpful? Give feedback.
-
|
By default, React Hook Form unregisters inputs when their components are unmounted from the DOM. When you use a conditional rendering switch-case pattern like Solution 1: Use CSS to hide/show steps (Recommended)Instead of unmounting step components conditionally, keep them all mounted in the DOM and toggle their visibility using CSS ( export default function CreateEventForm() {
// ...
return (
<Card className="max-w-3xl mx-auto">
<form onSubmit={form.handleSubmit(handleCreateEvent)}>
{/* Step 1 */}
<div className={currentStep === 0 ? "block" : "hidden"}>
<StepOneFields control={form.control} />
</div>
{/* Step 2 */}
<div className={currentStep === 1 ? "block" : "hidden"}>
<StepTwoFields control={form.control} />
</div>
{/* ...Other Steps */}
</form>
</Card>
);
}Solution 2: Lift state or separate schemas per stepIf you must completely unmount the steps, it is best practice to keep a local parent state to store the completed step data, or define a separate schema/resolver for each step. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm building a multi-step form using:
React Hook Form
Zod
Next.js (App Router)
Each step conditionally renders different fields using a switch(currentStep) pattern.
When I click Next to move to another step:
the isValid is set to true and allow me to move to the next step
but the previously filled values (e.g. title, shortDescription, platform) become undefined
form.watch() confirms the values are actually lost, not just UI
I would like to ask what might be the problem here
(The form is not finished yet)
Beta Was this translation helpful? Give feedback.
All reactions