Sub topic 10
Mutating data with actions and Form
This chapter assumes you know how a route module exports a loader and how app/routes.ts maps paths to files. It also assumes you are comfortable with HTML forms, FormData, and HTTP status codes. Here you will learn how an action receives a submission, how Form sends it, and what React Router does after the action finishes.
What an action is
An action is an exported function in a route module. It handles every non-GET request sent to that route: POST, PUT, PATCH, and DELETE. Loaders read data and actions change it. The action runs on the server, so it can use database clients and secrets safely.
React Router gives the action a standard Fetch API Request. You read the body with request.formData(), the same API you would use in a service worker or an edge function.
import { data, redirect } from "react-router";
import type { Route } from "./+types/new";
import { createContact } from "~/contacts.server";
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return data({ error: "Name is required" }, { status: 400 });
}
const contact = await createContact({ name });
return redirect(`/contacts/${contact.id}`);
}formData.get() returns FormDataEntryValue | null, which is a string, a File, or null. Convert and trim the value before you trust it. Validation has its own chapter, so here the check is only enough to show the two possible outcomes of an action: return data, or redirect.
The Form component
Form from react-router renders a normal <form>. When the user submits it, React Router intercepts the event, builds the request with fetch, and sends it to the route's action. The page does not reload.
import { Form } from "react-router";
export default function NewContact() {
return (
<Form method="post">
<input name="name" />
<button type="submit">Save</button>
</Form>
);
}Each field's name attribute becomes a key in FormData. A field without a name is not submitted. This is the most common reason formData.get("x") returns null.
| Prop | Effect |
|---|---|
| `method` | `post`, `put`, `patch`, or `delete` calls the action. `get` navigates and calls the loader with the fields as search parameters. |
| `action` | The route to submit to. It defaults to the closest route that renders the form. |
| `replace` | Replaces the current history entry instead of adding one. |
| `reloadDocument` | Does a full browser submission, bypassing client-side handling. |
Browsers only submit GET and POST natively. React Router sends the real method with fetch when JavaScript is available. In a plain server-rendered page before hydration, it falls back to a POST with a _method convention handled for you. In either case request.method in the action is the method you set.
The request lifecycle
Actions are tied to loaders through revalidation. After an action returns, React Router automatically calls the loaders of all routes on the current page again. The UI then shows fresh data without any manual cache invalidation.
If the action returns a redirect, the router follows it and loads the target route's data instead. If the action returns plain data or data(...), the current route stays mounted. The value appears as actionData in the component and the loaders revalidate. A thrown response or error goes to the nearest ErrorBoundary.
Handling several mutations in one route
A route has only one action. When a page needs several mutations, give each submit button an intent value and branch on it.
import { Form, data, redirect } from "react-router";
import type { Route } from "./+types/detail";
import { deleteContact, getContact, updateContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) throw data("Contact not found", { status: 404 });
return { contact };
}
export async function action({ params, request }: Route.ActionArgs) {
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "delete") {
await deleteContact(params.contactId);
return redirect("/contacts");
}
if (intent === "favorite") {
await updateContact(params.contactId, {
favorite: formData.get("favorite") === "true",
});
return null;
}
throw data("Unknown intent", { status: 400 });
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
const { contact } = loaderData;
return (
<div>
<h1>{contact.name}</h1>
<Form method="post">
<input type="hidden" name="favorite" value={String(!contact.favorite)} />
<button type="submit" name="intent" value="favorite">
{contact.favorite ? "Remove favorite" : "Add favorite"}
</button>
</Form>
<Form
method="post"
onSubmit={(event) => {
if (!confirm("Delete this contact?")) event.preventDefault();
}}
>
<button type="submit" name="intent" value="delete">
Delete
</button>
</Form>
</div>
);
}The browser includes the clicked button's name and value in the submission, so intent arrives in FormData without a hidden input. The final throw rejects values you did not expect, so an unknown intent never silently succeeds.
Redirect after a successful POST
Return a redirect after a successful create or delete. This follows the Post/Redirect/Get pattern. The browser's history entry then points at a GET page, so a refresh does not resubmit the form and the URL reflects the new state. Return data instead when the user should stay on the page, for example to show an error next to the field.
Edge cases and common errors
- No action exported. A non-GET submission to a route without an action produces a 405 response, which goes to an error boundary. Check that
Form'sactionprop points to the route you meant. - Form submitted to a layout. A
Formwith noactiontargets the closest route in the component tree. Inside a layout route, that is the layout's action. Addaction="/contacts/new"to target another route. - Index routes. A form on an index route without an
actionprop submits to the parent path with?index, so the index route's action runs and not the parent's. Rely on the default and avoid hand-written URLs here. - Plain
<form>. A lowercase<form>performs a full document request. It works, but you lose client-side navigation and pending state. - Reading the body twice.
request.formData()consumes the stream. Call it once, or userequest.clone(). - Revalidation cost. Every loader on the page runs again after each action. If this is expensive, a route can export
shouldRevalidateto skip it.
Exercise
A route exports an action that handles "rename" and "archive" submissions. The page has two Form components, and both use method="post" and no action prop. How does the action tell them apart, and what happens to the page's loaders after it returns?
Show answer
Give each submit button a name="intent" attribute with a distinct value, such as "rename" or "archive", and read formData.get("intent") in the action to branch. After the action returns data, or after the redirect is followed, React Router revalidates the loaders for the routes on the page, so loaderData shows the updated records.