Sub topic 7
Handling validation errors and failures
This chapter assumes you know the pieces covered earlier in this tutorial: useTransition, the <form action> prop with FormData, and useActionState. You should also be comfortable with try/catch and async/await.
An Action can go wrong in several ways. The user may type an invalid email. The server may reject a request because the email is already registered. The network may drop. Your own code may have a bug. React 19 gives you two paths for these cases, and picking the right one for each failure is most of the work.
Two kinds of failure
Expected failures are outcomes you can predict and explain to the user. Examples are an empty field, a duplicate username, or a 500 response. You handle these as data: the Action returns a value describing what went wrong, and the component renders it.
Unexpected failures are outcomes you did not plan for, such as a bug, a corrupted response, or a crash in your code. You handle these by letting the Action throw. React passes the error to the nearest error boundary, which shows fallback UI.
| Row | Expected failure | Unexpected failure |
|---|---|---|
| Example | "Email already taken" | `TypeError` from a bad response shape |
| How the Action reports it | Returns an object | Throws |
| Where it is shown | Next to the form fields | Error boundary fallback |
| Does `useActionState` update? | Yes, with the returned value | No, the thrown error replaces the tree |
| User can fix it? | Usually | Usually not |
A good rule: if the user can fix the problem by changing the input or retrying, return it. If not, throw.
Returning validation errors from useActionState
useActionState calls your Action with the previous state and the FormData. Whatever the Action returns becomes the new state. This makes validation a plain function: read the fields, check them, and return either errors or a success result.
import { useActionState } from "react";
const initialState = {
status: "idle",
values: { email: "" },
fieldErrors: {},
message: null,
};
function validate({ email, password }) {
const errors = {};
if (!email.includes("@")) {
errors.email = "Enter a valid email address.";
}
if (password.length < 8) {
errors.password = "Use at least 8 characters.";
}
return errors;
}
async function signUp(previousState, formData) {
const email = String(formData.get("email") ?? "").trim();
const password = String(formData.get("password") ?? "");
const fieldErrors = validate({ email, password });
if (Object.keys(fieldErrors).length > 0) {
return { status: "invalid", values: { email }, fieldErrors, message: null };
}
try {
const response = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (response.status === 409) {
return {
status: "invalid",
values: { email },
fieldErrors: { email: "That email is already registered." },
message: null,
};
}
if (!response.ok) {
return {
status: "failed",
values: { email },
fieldErrors: {},
message: "We could not create your account. Please try again.",
};
}
} catch {
return {
status: "failed",
values: { email },
fieldErrors: {},
message: "Network error. Check your connection and try again.",
};
}
return { status: "success", values: { email: "" }, fieldErrors: {}, message: "Account created." };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, initialState);
return (
<form action={formAction} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
defaultValue={state.values.email}
aria-invalid={Boolean(state.fieldErrors.email)}
aria-describedby={state.fieldErrors.email ? "email-error" : undefined}
/>
{state.fieldErrors.email && <p id="email-error">{state.fieldErrors.email}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
aria-invalid={Boolean(state.fieldErrors.password)}
aria-describedby={state.fieldErrors.password ? "password-error" : undefined}
/>
{state.fieldErrors.password && <p id="password-error">{state.fieldErrors.password}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Creating..." : "Sign up"}
</button>
{state.message && <p role="alert">{state.message}</p>}
</form>
);
}Several design choices in this example matter.
Why the state has a fixed shape
The state always has status, values, fieldErrors, and message. A stable shape means the component never has to check whether a property exists before reading state.fieldErrors.email. Add a status field so the UI can tell "never submitted" from "submitted and valid".
Why the Action echoes values back
React resets uncontrolled form fields after an Action finishes. This happens even when the Action returns an error. Without help, the user would lose everything they typed. The Action therefore returns the submitted values, and the inputs use defaultValue={state.values.email} to restore them.
The password is deliberately not echoed. It is cleared on every submit, which is the usual behavior for password fields.
Why a duplicate email is a field error
The server's 409 response is a failure the user can fix. The Action maps it to the same fieldErrors.email slot that client validation uses. The component renders one error location regardless of where the error originated.
Separating network failures from server rejections
fetch has two failure modes that look different in code:
- It rejects (throws) when the request cannot complete, for example when the user is offline. A
try/catchcatches this. - It resolves with
response.ok === falsewhen the server answers with a 4xx or 5xx status. No exception occurs, so you must checkresponse.ok.
Forgetting the second check is a common bug. The Action appears to succeed, the form resets, and the user sees nothing wrong, though the data was never saved. In the example above, each branch handles one case and returns a distinct message.
Parse the response body inside the try block when you need server-supplied messages. Calling response.json() on a non-JSON body throws, and you want that caught.
Letting unexpected errors reach an error boundary
If an Action throws and nothing catches it, React rethrows the error during render of the component that owns the Action. The nearest error boundary then replaces that part of the tree with its fallback UI. This applies to Actions run through useActionState, through a form's action prop, and through startTransition.
React still has no built-in error boundary component. You write a class component, or use a library such as react-error-boundary.
import { Component, useActionState } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return (
<div role="alert">
<p>Something went wrong.</p>
<button onClick={() => this.setState({ error: null })}>Try again</button>
</div>
);
}
return this.props.children;
}
}
async function deleteAccount() {
const response = await fetch("/api/account", { method: "DELETE" });
if (!response.ok) {
throw new Error(`Delete failed with status ${response.status}`);
}
return { deleted: true };
}
function DeleteForm() {
const [state, formAction, isPending] = useActionState(deleteAccount, { deleted: false });
return (
<form action={formAction}>
<button type="submit" disabled={isPending}>Delete account</button>
{state.deleted && <p>Account deleted.</p>}
</form>
);
}
export function DeleteAccountSection() {
return (
<ErrorBoundary>
<DeleteForm />
</ErrorBoundary>
);
}Here a failed delete throws, and the boundary shows a generic message. That is acceptable for an operation the user cannot meaningfully retry with different input. For a form the user could correct, returning an error is friendlier, because a boundary discards the form and the user's input with it.
Errors in useTransition
The first chapter of this section showed an Action run with startTransition. Here the same two rules apply: handle expected failures in your own code, and let unexpected ones throw.
import { useState, useTransition } from "react";
async function renameProject(id, name) {
const response = await fetch(`/api/projects/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error("Rename failed");
}
}
export function RenameProject({ id }) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
function handleClick() {
startTransition(async () => {
try {
await renameProject(id, name);
startTransition(() => setError(null));
} catch {
startTransition(() => setError("Could not rename the project."));
}
});
}
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleClick} disabled={isPending}>Rename</button>
{error && <p role="alert">{error}</p>}
</div>
);
}The startTransition calls around setError after the await are intentional. React tracks a transition only for state updates made synchronously inside the function. Anything after an await is outside it. Wrapping later updates in another startTransition keeps them marked as transition updates. Skipping the wrapper does not break the example, but the update is then treated as urgent rather than as part of the transition.
With useTransition, you own the error state yourself. With useActionState, the returned state serves that purpose, which is why it is the better fit for forms.
Order of execution
useActionState runs queued submissions one at a time, in order. If a user double-clicks Submit, the second call receives the state returned by the first. Disabling the button with isPending still helps, because it prevents duplicate requests. Do not rely on it alone for correctness, since the server must also reject duplicates.
Making errors accessible
Errors that only appear visually can be missed by screen reader users. The first example uses three techniques:
aria-invalidmarks a field as failing validation.aria-describedbypoints to the element holding the field's error text, so the message is read with the field.role="alert"on the general message makes assistive technology announce it when it appears.
Setting noValidate on the form turns off the browser's built-in validation bubbles, so your own messages are the ones users see. If you prefer native validation, remove noValidate and keep required and type="email" on the inputs. Either way, validate again inside the Action. Browser checks are a convenience and are easy to bypass.
Common mistakes
- Not returning submitted values. The form resets, and users retype everything after one mistake.
- Ignoring
response.ok. A 500 response looks like success. - Throwing for validation. The boundary discards the form instead of showing a hint beside the field.
- Swallowing real bugs. A bare
catchthat returns a friendly message hides programming errors. Catch only what you can describe to the user, and log the rest. - Trusting client validation. Anyone can send a request without your form. Validate on the server too.
- Reading
FormDatavalues as the wrong type.formData.getreturnsstring,File, ornull. Wrapping it inString(... ?? "")avoids crashes on missing fields.
Exercise
A checkout Action calls fetch("/api/order"), and the server replies with status 500. The Action has try/catch but no response.ok check, and it returns { status: "success" } at the end. What does the user see, and how do you fix it?
Show answer
The user sees a success state, because fetch resolves normally for HTTP 500 and the catch block never runs. The form also resets, so the order looks placed when it is not. Fix it by checking if (!response.ok) after the fetch and returning a failure state, for example { status: "failed", message: "We could not place your order. Please try again." }. Also return the submitted values so the form can restore its fields.
Exercise
Your profile form's Action finds that the display name is longer than 40 characters. Should it throw an error or return state? Explain, and name one situation where throwing is the better choice.
Show answer
It should return state, for example { fieldErrors: { displayName: "Use 40 characters or fewer." }, values: { displayName } }. The user can fix this, and returning keeps the form mounted so the error appears next to the field. Throwing would send the error to the error boundary and discard the form. Throwing is better for failures the user cannot correct and that point to a bug or broken system, such as the server returning data in an unexpected shape.