Sub topic 14
Submitting to an API and showing server errors
This chapter assumes you can build a form with useForm, register, and handleSubmit, and that you have connected a Zod schema with zodResolver. It also assumes you are comfortable with async/await.
Why the schema is not enough
A Zod schema checks what the browser can know. It cannot know whether an email is already registered or whether a coupon code is still valid. Only the server can answer those questions, so a submission can fail even after the schema passes.
The goal is to show these failures in the same place as client-side errors: formState.errors. Then the UI needs only one way to display problems.
What handleSubmit does for you
handleSubmit runs your resolver first. If validation fails, it fills errors and does not call your function. If validation passes, it calls your onSubmit with the validated values.
If onSubmit returns a promise, formState.isSubmitting is true until that promise settles. You can use it to disable the button and prevent double submits.
Mapping a server failure to a field
setError comes from the useForm return value. It writes an entry into errors for a field name you choose.
const onSubmit = async (values: SignUpValues) => {
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
setError("email", {
type: "server",
message: "This email is already registered",
});
return;
}
};Your existing JSX, {errors.email && <p role="alert">{errors.email.message}</p>}, now shows the server message with no change. The type value is a label you pick. It lets you tell server errors apart from schema errors if you need to.
To use this, destructure setError next to register and handleSubmit:
const {
register,
handleSubmit,
setError,
formState: { errors, isSubmitting },
} = useForm<SignUpValues>({ resolver: zodResolver(signUpSchema) });Errors that belong to the whole form
Some failures, such as a network error or a 500 response, do not belong to one field. React Hook Form reserves the root key for these.
try {
const response = await fetch("/api/sign-up", { method: "POST" });
if (!response.ok) throw new Error("Request failed");
} catch {
setError("root.server", {
message: "Something went wrong. Please try again.",
});
}Read it with errors.root?.server?.message.
Common mistakes
- Stale server errors.
setErrorerrors on a field are cleared the next time that field passes validation, and they are cleared when the form is submitted again. Root errors are not cleared by editing a field, so show them near the submit button and expect them to reset on the next submit. - Swallowed failures.
fetchdoes not throw on 4xx or 5xx. Checkresponse.okorresponse.statusyourself. - Throwing from onSubmit. An unhandled throw leaves you with an unhandled rejection. Catch it and call
setError.
Exercise
A user submits a valid sign-up form and the server replies with status 500. fetch does not throw. What should onSubmit do so the user sees a message, and where should the message be read from?
Show answer
Check response.ok. When it is false, call setError("root.server", { message: "..." }) and return. Display errors.root?.server?.message near the submit button, because the failure belongs to the whole form and not to one field.