fix(presentation): single-flight form submit and clean state before navigation (Q-6.8-13b)

useAppForm holds one submission from validation to outcome, so a second
submit during an async refine returns the running submission instead of
submitting again (the pending ref used to be set only after
safeParseAsync). A successful save commits its settled values with
flushSync before submitForm resolves, so a navigate() right after the
save meets a clean form and the dirty guard does not ask to discard.

Verified with two new form-foundation cases (RED: submit ran twice; the
discard dialog blocked navigation) and the lane gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 13:44:38 +09:00
co-authored by Claude Opus 5.5
parent 11eb0dc0e0
commit cc1c7d879c
2 changed files with 124 additions and 20 deletions
+35 -20
View File
@@ -7,6 +7,7 @@ import {
type ChangeEvent,
type FormEvent,
} from "react";
import { flushSync } from "react-dom";
import type { ZodType, ZodIssue } from "zod";
import {
useLocale,
@@ -63,7 +64,7 @@ export function useAppForm<
const [formErrors, setFormErrors] = useState<readonly string[]>([]);
const [pending, setPending] = useState(false);
const [result, setResult] = useState<FormResultState>("idle");
const pendingRef = useRef<Promise<FormResult<Output>> | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
const unknownSubmissionRef = useRef<Values | null>(null);
const dirty = useMemo(
@@ -142,16 +143,20 @@ export function useAppForm<
const settleSuccessfulValues = useCallback(
(settledValues: Values) => {
unknownSubmissionRef.current = null;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
setInitialValues(defaultValues);
setTouched(new Set());
} else {
setInitialValues(settledValues);
}
// Committed before the caller continues: a `navigate()` right after a
// save must meet a clean form, not the dirty guard of the last render.
flushSync(() => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
setInitialValues(defaultValues);
setTouched(new Set());
} else {
setInitialValues(settledValues);
}
});
},
[defaultValues, resetOnSuccess],
);
@@ -170,11 +175,8 @@ export function useAppForm<
setResult("idle");
}, []);
const submitForm = useCallback(
async (event?: FormEvent<HTMLFormElement>): Promise<FormResult<Output> | null> => {
event?.preventDefault();
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return null;
const validateAndSubmit = useCallback(
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
@@ -201,10 +203,8 @@ export function useAppForm<
const command = mapToCommand(parsed.data);
setPending(true);
const execution = submit(command);
pendingRef.current = execution;
try {
const outcome = await execution;
const outcome = await submit(command);
if (outcome.ok) {
settleSuccessfulValues(parsed.data);
return outcome;
@@ -239,7 +239,6 @@ export function useAppForm<
}
return outcome;
} finally {
pendingRef.current = null;
setPending(false);
}
},
@@ -255,6 +254,22 @@ export function useAppForm<
],
);
const submitForm = useCallback(
(event?: FormEvent<HTMLFormElement>): Promise<FormResult<Output> | null> => {
event?.preventDefault();
// One submission from validation to outcome: an async refine must not
// let a second submit through before the command starts.
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return Promise.resolve(null);
const submission = validateAndSubmit().finally(() => {
pendingRef.current = null;
});
pendingRef.current = submission;
return submission;
},
[validateAndSubmit],
);
return Object.freeze({
formId,
values,
+89
View File
@@ -278,3 +278,92 @@ describe("dirty navigation guard", () => {
expect(await screen.findByRole("heading", { name: "Target" })).toBeVisible();
});
});
describe("submission timing", () => {
it("submits once when a second submit arrives during async validation", async () => {
const user = userEvent.setup();
let releaseValidation: () => void = () => {};
const validationGate = new Promise<void>((resolve) => {
releaseValidation = resolve;
});
const asyncSchema = schema.refine(async () => {
await validationGate;
return true;
});
const submit = vi.fn(async () => ({ ok: true as const, value: "saved" }));
function AsyncForm() {
const form = useAppForm({
schema: asyncSchema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit,
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Submit</Button>
<output data-testid="result">{form.result}</output>
</Form>
);
}
render(<AsyncForm />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Submit" }));
await user.click(screen.getByRole("button", { name: "Submit" }));
releaseValidation();
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(submit).toHaveBeenCalledOnce();
});
it("does not ask to discard changes when navigating right after a save", async () => {
const user = userEvent.setup();
function SaveThenLeave() {
const navigate = useNavigate();
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: async () => ({ ok: true as const, value: "saved" }),
});
const guard = useDirtyNavigationGuard(form.dirty);
return (
<Form
onSubmit={(event) => {
void form.submitForm(event).then((outcome) => {
if (outcome?.ok) void navigate("/done");
});
}}
pending={form.pending}
>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Save</Button>
<DirtyNavigationDialog guard={guard} />
</Form>
);
}
const router = createMemoryRouter(
[
{ path: "/", element: <SaveThenLeave /> },
{ path: "/done", element: <h1>Done</h1> },
],
{ initialEntries: ["/"] },
);
render(<RouterProvider router={router} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("heading", { name: "Done" })).toBeVisible();
expect(
screen.queryByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }),
).not.toBeInTheDocument();
});
});