Sub topic 10
Mutating data with actions and Form
This chapter assumes you know React components and hooks, TypeScript basics, HTTP methods and status codes, and the browser's FormData API. It also assumes you have read the chapters on route configuration and loaders.
The working model
A loader reads data. An action changes it. Each route module can export an action function that runs on the server when a non-GET request (POST, PUT, PATCH, DELETE) is sent to that route.
The Form component from react-router renders a normal HTML <form>. When the user submits it, React Router intercepts the event, sends a fetch request to the route's action, and avoids a full page reload. If JavaScript has not loaded yet, the browser submits the form natively and the same action still runs.
After an action finishes, React Router automatically calls the loaders of the routes on the page again. Your UI shows fresh data without manual cache invalidation.
A complete action
The action receives the standard Request object. Read the body with request.formData().
import { Form, data, redirect, useNavigation } 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}`);
}
export default function NewContact({ actionData }: Route.ComponentProps) {
const navigation = useNavigation();
const saving = navigation.state === "submitting";
return (
<Form method="post">
<input name="name" />
{actionData?.error ? <p role="alert">{actionData.error}</p> : null}
<button type="submit" disabled={saving}>
{saving ? "Saving..." : "Save"}
</button>
</Form>
);
}The pieces work like this:
formData.get("name")returns aFormDataEntryValue, which is a string or aFile, ornull. Converting withString(... ?? "")gives you a string to validate.data(body, { status: 400 })returns a value with a custom status. The value arrives in the component asactionData.redirect(path)sends the browser to a new URL. Use it after a successful mutation so a page refresh does not resubmit the form.useNavigation().stateis"idle","submitting", or"loading". It lets you disable the button while the request is in flight.
Choosing the return value
| Outcome | Return | Result |
|---|---|---|
| Success | `redirect(...)` | Browser navigates, loaders run |
| Invalid input | `data({ error }, { status: 400 })` | Same page re-renders with `actionData` |
| Missing or forbidden resource | `throw data("...", { status: 404 })` | Nearest `ErrorBoundary` renders |
Common errors
- Using a plain
<form>or lowercaseform. WithoutForm, you get a full page reload and lose client-side state. - Omitting
method="post". The default method is GET, which runs the loader with the fields as query parameters, not the action. - Missing
nameattributes. Inputs without anameare not included inFormData. - Trusting client validation. The action is a server endpoint. Always validate there, even if the browser also checks.
- Returning errors with status 200. Use 400 (or 422) so the response status matches the outcome.
Exercise
A user submits a valid form and then presses the browser's refresh button. Why does the app not create a duplicate record when the action ends with redirect?
Show answer
After the redirect, the current page is a GET request to the new URL, not the original POST. Refreshing repeats that GET, which only runs loaders, so the action does not run again.
Exercise
Your form has <Form> with an input named title, but formData.get("title") always returns null and the action logs a GET request. What is the most likely cause?
Show answer
The form is missing method="post", so it defaults to GET and sends the fields as query parameters. The action runs only for non-GET methods. Adding method="post" fixes it.