Sub topic 7
Handling validation errors and failures
This chapter assumes you know useActionState, form action functions, and FormData, and that you can read async/await and fetch. It covers what an Action should do when something goes wrong, and where each kind of problem should go.
Two kinds of problems
An Action can fail in two different ways, and each needs a different treatment.
- Expected problems are things like an empty field, a taken email address, or a 400 response. They are part of normal use. Return them as data and show them next to the form.
- Unexpected problems are things like a crashed server or a bug in your code. The user cannot fix them by editing the form. Let them throw so an error boundary can show a fallback.
Return validation errors as state
useActionState stores whatever your Action returns. That makes the return value the natural place for validation results. Return an object with the error messages and the submitted values.
The submitted values matter because React resets uncontrolled form fields after the Action finishes. If you only return an error, the user's input disappears. Returning the values lets you put them back with defaultValue.
import { useActionState } from "react";
async function signUp(previousState, formData) {
const email = String(formData.get("email") ?? "").trim();
if (!email.includes("@")) {
return { ok: false, email, errors: { email: "Enter a valid email address." } };
}
try {
const response = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
if (response.status === 409) {
return { ok: false, email, errors: { email: "That email is already registered." } };
}
if (!response.ok) {
return { ok: false, email, errors: { form: "The server had a problem. Try again." } };
}
} catch {
return { ok: false, email, errors: { form: "Network error. Check your connection." } };
}
return { ok: true, email: "", errors: {} };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, {
ok: false,
email: "",
errors: {},
});
return (
<form action={formAction}>
<input
name="email"
defaultValue={state.email}
aria-invalid={Boolean(state.errors.email)}
/>
{state.errors.email && <p role="alert">{state.errors.email}</p>}
{state.errors.form && <p role="alert">{state.errors.form}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Signing up..." : "Sign up"}
</button>
{state.ok && <p>Thanks, you are signed up.</p>}
</form>
);
}Each result has the same shape: ok, email, and errors. A consistent shape means the component never has to check whether a field exists before reading it.
Check the response, not just the promise
fetch rejects only when the request cannot be completed, for example when the network is down. A 400 or 500 response still resolves. If you skip response.ok, your Action will treat a server error as success.
The example above handles both cases. response.ok and response.status cover HTTP failures. The try/catch covers requests that never completed. In both cases the Action returns an error message instead of throwing, because the user can retry.
Let unexpected errors throw
If an Action throws, React stops the transition and rethrows the error during render. The nearest error boundary then renders its fallback. This is right for bugs and for failures you cannot present inline. Wrap the form, or the part of the page that depends on it, in an error boundary so a thrown error does not blank the whole app.
The same rule applies to an async function passed to startTransition. A thrown error reaches an error boundary. An error you catch and store with setError stays under your control, as in the earlier useTransition example.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Returning only an error message | Typed values vanish after the form resets | Return the submitted values and use `defaultValue` |
| Ignoring `response.ok` | A 500 response looks like success | Check `response.ok` before returning success |
| Throwing for validation | The error boundary replaces the form | Return the error as state |
| Different state shapes per branch | `state.errors.email` throws a `TypeError` when `errors` is missing | Return the same keys every time |
| Validating only in the browser | Direct requests skip your checks | Validate again on the server |
The last row matters most. Client-side checks improve the experience, but they do not protect your data. A later chapter returns to this for Server Functions.
Exercise
A user submits a form whose Action calls fetch, and the server responds with status 500. The Action contains no response.ok check and no try/catch. What does the user see, and what two changes make the failure visible and recoverable?
Show answer
The promise resolves, so the Action finishes as if it succeeded. The form resets and shows no error. Add a response.ok check that returns an error state such as { errors: { form: "..." } }, and wrap the fetch in try/catch so network failures also return an error state. Return the submitted values too, so the user does not lose their input.