Submit
Validate, save, and show how the save went.
onSubmit on the definition runs when the user submits a valid form. What
it returns is the submission’s result, and it may be async. The form’s state
tracks the submit while it runs. Try [email protected] in the demo.
onSubmit
const account = forms.define({
defaultValues: { name: "", email: "" },
onSubmit: async (value, { store, signal }) => {
const response = await fetch("/api/account", {
method: "PUT",
body: JSON.stringify(value),
signal,
});
return response.json();
},
});value is a copy of the form’s value, which you may change without touching
the form. With a schema it is the schema’s output.
The second argument has:
store, the form’s store, forsetErrorsand the rest.signal, which aborts when the form is reset while the submit runs.intent, the value passed toform.submit(intent). See Intents.input, the form value that passed validation, before the schema transformed it.
What a submit does
Spreading formProps on the <form> element wires its submit event to
form.handleSubmit. A submit then:
- Clears the errors the last submit set with
setErrors, counts the submit, and sets the status to"submitting". - Runs validation, and waits for async validators to finish.
- Stops with status
"invalid"if any field has an error, and moves focus to the first invalid field.onSubmitisn’t called. - Otherwise calls
onSubmit. Its return value ends the submit as"succeeded", and a throw as"failed".
A submit while one is running doesn’t start another. It returns the running one.
To submit from code, call form.submit(). It resolves to the submission.
Turn off the focus move with focusOnInvalid: false on createForms, or
pass a function to handle it yourself.
Submit state
The form snapshot has the state of the latest submit:
| Member | What it is |
|---|---|
submitting |
True while a submit runs. |
submission |
{ status }: "idle", "submitting", "invalid", "succeeded" with result, or "failed" with error. |
submitCount |
How many submits have started, including invalid ones. |
valid, validating |
No validation errors, a validator running. |
Read it with useFormState(form, select), which re-renders only when the
selected part changes, or inline with form.State:
const submitting = useFormState(form, (state) => state.submitting);
<form.State select={(state) => state.submission}>
{(submission) => (submission.status === "failed" ? <p>Something went wrong.</p> : null)}
</form.State>;A component under form.Form gets the form from useFormContext(forms),
so a submit button needs no props.
When the server says no
A server that refuses the save usually says why. Put that on the form with
store.setErrors and return:
onSubmit: async (value, { store }) => {
const response = await saveAccount(value);
if (!response.ok) {
store.setErrors({
form: { message: "Nothing was saved." },
fields: { email: { message: "That email is taken." } },
});
return null;
}
return `Saved ${value.name}.`;
},fields is keyed by field name. form errors land on the form’s root
field, so render the root’s errors somewhere, or the user sees nothing. See
submit:unseen for how.
A name that matches no field also lands on the root, after the form
errors, and development warns with
field:unknown. That happens when the server
renames a field before the form catches up. A name counts as a field when the
value has that key, when a field there is rendered or validated, or when it
sits under an object that is missing. To send such errors somewhere else,
such as a toast, check each name with store.pathOf first:
// The names to show in a toast instead.
const unknown = Object.keys(response.fields).filter((name) => store.pathOf(name) === undefined);Errors set this way don’t block the next submit. Each one clears when the user edits its field, and they all clear when the next submit starts.
Error summary
A long form can list its errors at the top, so the user sees what the server
refused without scrolling. Each entry has the field’s name, its errors,
and its handle as field, whose id is the input’s id. The root comes first
with name "", and the rest follow in form order. The list counts errors from
validation and from setErrors alike.
function Summary() {
const form = useFormContext(forms);
const invalid = useInvalidFields(form);
return (
<ul>
{invalid.map((entry) => (
<li key={entry.field.id}>
<a href={`#${entry.field.id}`}>{entry.name || "Form"}</a>:{" "}
{entry.errors.map((error) => error.message).join(" ")}
</li>
))}
</ul>
);
}A submit that validation stops moves focus to the first invalid field. One
that onSubmit ends with setErrors doesn’t, since the submit itself
succeeded. To focus the first field the server refused, call
store.firstInvalid() after the submit resolves:
await form.submit();
const field = form.store.firstInvalid();
if (field) document.getElementById(field.id)?.focus();A plugin can refuse a submit too. Its onSubmit hook returns refuse, and
the submit ends "invalid" without calling yours. See
Writing a plugin.
Intents
A form with two submit buttons, such as Save draft and Publish, can pass an
intent. Annotate ctx.intent to type it:
const post = forms.define({
defaultValues: { title: "", body: "" },
onSubmit: (value, ctx: { intent: "draft" | "publish" }) => save(value, ctx.intent),
});Then call form.submit("draft") or form.submit("publish") from each
button’s click. submit() with no intent is now a type error, and the
<form>’s own submit event submits with an undefined intent.
Last updated