diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 663b0cb1..bf389ab3 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -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([]); const [pending, setPending] = useState(false); const [result, setResult] = useState("idle"); - const pendingRef = useRef> | null>(null); + const pendingRef = useRef | null> | null>(null); const unknownSubmissionRef = useRef(null); const dirty = useMemo( @@ -142,16 +143,20 @@ export function useAppForm< const settleSuccessfulValues = useCallback( (settledValues: Values) => { unknownSubmissionRef.current = null; - setFieldErrors({} as FieldErrors); - 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); + 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): Promise | null> => { - event?.preventDefault(); - if (pendingRef.current) return pendingRef.current; - if (unknownSubmissionRef.current) return null; + const validateAndSubmit = useCallback( + async (): Promise | null> => { setFieldErrors({} as FieldErrors); 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): Promise | 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, diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 7ad8b7e6..1711148d 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -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((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 ( +
void form.submitForm(event)}> + + + {form.result} + + ); + } + + render(); + 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 ( +
{ + void form.submitForm(event).then((outcome) => { + if (outcome?.ok) void navigate("/done"); + }); + }} + pending={form.pending} + > + + + + + ); + } + + const router = createMemoryRouter( + [ + { path: "/", element: }, + { path: "/done", element:

Done

}, + ], + { initialEntries: ["/"] }, + ); + render(); + 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(); + }); +});