Sub topic 11
Submitting data with actions and Form
This chapter assumes you can define routes and loaders with createBrowserRouter, and that you are comfortable with async/await, fetch, and the browser's FormData.
What an action is
A loader reads data for a route. An action writes data. An action is a function attached to a route. React Router calls it when a Form submits to that route with a method other than GET. The action receives a request object, so it can read the submitted fields, send them to your API, and then return a result or a redirect.
You don't write onSubmit handlers, preventDefault calls, or useState for each field. The browser's form model does that work, and the router intercepts the submission so the page doesn't reload.
The submission cycle
After an action finishes, the router automatically re-runs the loaders on the page. Lists and detail views therefore show fresh data without any manual refetching.
A working example
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 }Here is how the pieces fit together:
Form method="post"submits to the closest route that has an action. Here that iscontacts/new.request.formData()returns aFormDataobject. It is asynchronous, so you mustawaitit.formData.get("name")reads the field by itsnameattribute.redirect("/contacts")sends the user to a new page after a successful save.useNavigation().stateis"idle","submitting", or"loading". The example uses it to disable the button while the request runs.
Returning errors instead of redirecting
An action can return plain data instead of a redirect. Read it in the component with useActionData. This suits validation errors, because the user stays on the form with their input intact.
import { Form, useActionData } from "react-router-dom";
export async function validateAction({ request }) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return { error: "Name is required" };
}
return null;
}
export function ValidatedForm() {
const actionData = useActionData();
return (
<Form method="post">
<input name="name" />
{actionData?.error && <p role="alert">{actionData.error}</p>}
<button type="submit">Save</button>
</Form>
);
}Common errors
- Using a lowercase
<form>. A plain HTML form triggers a full page load and bypasses the action. ImportFormfromreact-router-dom. - Omitting
method="post". The default is GET. A GET submission only updates the query string and runs loaders. It never calls the action. - Missing
nameattributes. Inputs without anameare left out ofFormData, sogetreturnsnull. - Forgetting
awaitonrequest.formData(). You get a Promise, not the data. - Returning
undefined. Loaders and actions must return a value or throw. Returnnullwhen there is nothing to send back.
Exercise
A developer writes <form method="post"> with a plain lowercase tag inside a route that has an action. Clicking submit reloads the whole page and the action never runs. What is wrong, and what is the fix?
Show answer
A lowercase <form> is the browser's native form, so it makes a full-page request and the router never intercepts it. Import Form from react-router-dom and use <Form method="post">. The router then calls the route's action without a reload.