Controlled Select Element Loses Value After Form Submission with useActionState #81393
-
Hi there, What can I do in this situation? Move to javascript query selectors? I left a very simple example of my problem below which also does not do what I want it to. Form: "use client";
import { useActionState, useEffect, useState } from "react";
import { saveFormData } from "./actions";
type FormState = {
group: string;
};
const defaultState: FormState = {
group: "Junior",
};
export default function FormExample() {
const [state, formAction] = useActionState(saveFormData, defaultState);
const [group, setGroup] = useState(state.group);
useEffect(() => {
setGroup(state.group);
}, [state.group]);
return (
<form action={formAction}>
<label>
Group:
<select
name="group"
value={group}
onChange={(e) => setGroup(e.target.value)}
>
<option value="Mini">Mini (11–12)</option>
<option value="Junior">Junior (12–14)</option>
<option value="Senior">Senior (15+)</option>
</select>
</label>
<button type="submit" className="btn">
Submit
</button>
</form>
);
} Server action: "use server";
export async function saveFormData(prevState: unknown, formData: FormData) {
const group = String(formData.get("group"));
console.log("group on server: ", group);
// Persist values here (e.g., database, cookies, etc.)
return { group };
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
This issue occurs because Problem Summary
✅ Fix 1: Sync State with
|
Beta Was this translation helpful? Give feedback.
-
Hi, There's a bug with the select input not opting out from form reset behavior.
I found a hack on that thread though: <select
key={state.group}
name="group"
defaultValue={state.group}
onChange={(e) => setGroup(e.target.value)}
> Using |
Beta Was this translation helpful? Give feedback.
As they list in those threads, it is probably best to go with onSubmit for now, and avoid hacks and workarounds, onSubmit is still a valid way to do this ~ x-ref to that bug on a comment on your implementation, so that at some point you can update it.