Sub topic 11
Submitting data with actions and Form
This chapter covers how a route handles writes. You will define an action, submit to it with the Form component, and see how the router revalidates loader data afterward. It assumes you know loaders and useLoaderData, route objects, redirect, and JavaScript fetch with async/await. It also assumes you know how an HTML form posts data.
What an action is
A loader reads data before a route renders. An action does the opposite: it handles a write, such as creating or deleting a record. An action is an async function attached to a route through the action property. The router calls it when a form is submitted to that route with a method other than GET.
The action receives an object with two useful properties:
requestis a standard Fetch APIRequest. You read the submitted fields withawait request.formData().paramsholds the dynamic segments of the matched route, the same valuesuseParamsreturns.
The action can return a value, return a redirect, or throw. Each outcome has a different effect, covered below.
The Form component
Form from react-router-dom looks like an HTML <form>, but the router intercepts the submit event. It does not reload the page. It serializes the fields, calls the action of the matching route, and then updates the UI.
import { Form, redirect, useNavigation } from "react-router-dom";
export async function createContactAction({ request }) {
const formData = await request.formData();
const name = formData.get("name");
await fetch("/api/contacts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
return redirect("/contacts");
}
export function NewContact() {
const navigation = useNavigation();
const busy = navigation.state === "submitting";
return (
<Form method="post">
<input name="name" required />
<button type="submit" disabled={busy}>{busy ? "Saving..." : "Save"}</button>
</Form>
);
}
// Route definition: { path: "contacts/new", element: <NewContact />, action: createContactAction }Three details matter here.
- Each input needs a
nameattribute.formData.get("name")reads by that name, and inputs without one are not submitted. method="post"sends the submission to the action. Without a method, the form uses GET.- With no
actionprop onForm, it submits to the closest route that is rendering it. You can setaction="/other/path"to target a different route.
What happens during a submission
The sequence is the same every time. The router calls the action. When it finishes, the router revalidates: it re-runs the loaders of the routes currently on screen, so lists and details reflect the change. Then the UI updates.
You do not call a "refetch" function or update state by hand. Revalidation is why the data stays correct after a write.
Action outcomes
| Action does | Router does |
|---|---|
| Returns `redirect("/path")` | Navigates to the path. The loaders for the new location run. |
| Returns data (any value) | Stays on the page, revalidates loaders, and exposes the value through `useActionData`. |
| Throws an error or a `Response` | Renders the nearest `errorElement`. |
Redirecting after a successful create is the common pattern. It mirrors the "post, redirect, get" practice of server-rendered sites, and it prevents a refresh from resubmitting the form.
Returning validation errors
Throwing is wrong for validation problems, because the user should stay on the form with their input visible. Return an object instead and read it with useActionData.
import { Form, redirect, useActionData, useNavigation } from "react-router-dom";
export async function signupAction({ request }) {
const formData = await request.formData();
const email = String(formData.get("email") ?? "").trim();
if (!email.includes("@")) {
return { errors: { email: "Enter a valid email address." } };
}
const res = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
if (!res.ok) {
throw new Response("Signup failed", { status: res.status });
}
return redirect("/welcome");
}
export function Signup() {
const actionData = useActionData();
const navigation = useNavigation();
const submitting = navigation.state === "submitting";
return (
<Form method="post">
<label>
Email
<input name="email" type="email" defaultValue="" />
</label>
{actionData?.errors?.email ? <p role="alert">{actionData.errors.email}</p> : null}
<button type="submit" disabled={submitting}>
{submitting ? "Sending..." : "Sign up"}
</button>
</Form>
);
}useActionData returns undefined until the action has returned something, so use optional chaining. The pattern is to return for problems the user can fix and throw for failures the user cannot fix, such as a server error.
Several actions on one route
A route has one action function, but a page can hold several forms. A common technique is to read request.method or a hidden field to decide what to do. Forms can use method="post", "put", "patch", or "delete".
import { Form, redirect } from "react-router-dom";
export async function contactAction({ request, params }) {
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "delete") {
await fetch(`/api/contacts/${params.contactId}`, { method: "DELETE" });
return redirect("/contacts");
}
if (intent === "rename") {
await fetch(`/api/contacts/${params.contactId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: formData.get("name") }),
});
return null;
}
throw new Response("Unknown intent", { status: 400 });
}
export function ContactActions() {
return (
<>
<Form method="post">
<input name="name" />
<button type="submit" name="intent" value="rename">Rename</button>
</Form>
<Form method="post">
<button type="submit" name="intent" value="delete">Delete</button>
</Form>
</>
);
}The submit button's name and value are included in the form data, so the button that was clicked identifies the intent. Note that browsers only send GET and POST from plain HTML forms. React Router's Form accepts delete and patch because the router handles the submission itself.
Common errors
- Forgetting
method="post". A GET form does not call the action. It navigates to the same URL with the fields in the query string and runs loaders. - Missing
nameon inputs. The action receives an empty value for that field. - Using a plain
<form>. It causes a full page reload and bypasses the router. UseForm. - Returning
undefinedfrom an action. Returnnullwhen you have nothing to return. Loaders and actions in the data router must not returnundefined. - Throwing for validation errors. The user loses the form and sees the error page. Return the errors instead.
- Not awaiting the write. If you do not
awaitthefetch, the router revalidates before the write finishes and shows stale data. - Putting an action on the wrong route. The target is the route that
Formresolves to. In a nested layout, aFormwith noactionprop posts to the closest route that renders it. Check which route owns the action.
Exercises
Exercise
A user submits a Form with method="post" and the action returns redirect("/contacts"). Describe what the router does next, and say what a refresh on /contacts does.
Show answer
The router navigates to /contacts and runs the loaders for that location, so the contact list shows the new record. A refresh on /contacts only re-requests that URL with GET and does not resubmit the form, because the browser history entry is the redirect target and not the POST.
Exercise
An action checks that a required field is empty. Should it throw a Response or return an object? Explain, and name the hook that reads the result.
Show answer
It should return an object, for example { errors: { name: "Required" } }. The user stays on the form with their input, and the component reads the result with useActionData. Throwing renders the route's errorElement and replaces the form, which suits unrecoverable failures such as a server error.
Exercise
A page has a Rename form and a Delete form, both posting to the same route action. How does the action tell them apart?
Show answer
Give each submit button a name and value, such as name="intent" value="delete". The button's pair is included in the form data, so the action reads formData.get("intent") and branches on it. A hidden input with a name works as well.