Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Actions and Forms

Actions Basics

Learn how actions in React Router v7 framework mode handle POST, PUT and DELETE requests, read FormData, redirect after success, and trigger automatic revalidation.

Loaders read data; actions change it. An action is a function exported from a route module that runs on the server when the route receives a non-GET request (POST, PUT, PATCH or DELETE). After it finishes, the router automatically reruns the loaders of the current page so the UI shows fresh data. This is the whole mutation story: no manual cache invalidation, no state-sync code.

The framework cannot run on this site, so the real code is read-only. The stand-ins use the standard Request and FormData objects, which exist in Node, to show what an action actually does.

A first action

TSX
// app/routes/notes.new.tsx
import { Form, redirect } from "react-router";
import type { Route } from "./+types/notes.new";
import { createNote } from "~/models/note.server";

export async function action({ request }: Route.ActionArgs) {
  const formData = await request.formData();
  const title = String(formData.get("title") ?? "").trim();
  const body = String(formData.get("body") ?? "").trim();

  const note = await createNote({ title, body });
  return redirect(`/notes/${note.id}`);
}

export default function NewNote() {
  return (
    <Form method="post">
      <label>Title <input name="title" required /></label>
      <label>Body <textarea name="body" /></label>
      <button type="submit">Save</button>
    </Form>
  );
}

The flow is the classic web one, made smooth:

  1. The browser posts the form (JavaScript intercepts it, but it works without JavaScript too).
  2. action runs on the server, reads request.formData(), writes to the database.
  3. It returns a redirect to the new note (the post/redirect/get pattern: refreshing the page does not resubmit the form).
JS Stand-in: an action that reads FormData

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Methods and the _method idea

Browsers can only submit GET and POST in plain HTML forms. React Router's <Form method="delete"> and useFetcher send the real method when JavaScript is available. In the action, branch on request.method:

TSX
export async function action({ request, params }: Route.ActionArgs) {
  switch (request.method) {
    case "PUT": {
      const form = await request.formData();
      await updateNote(params.id, Object.fromEntries(form));
      return { ok: true };
    }
    case "DELETE": {
      await deleteNote(params.id);
      return redirect("/notes");
    }
    default:
      throw new Response("Method not allowed", { status: 405 });
  }
}

When one form has several buttons, name them the same and read the value (the intent pattern):

TSX
<button name="intent" value="archive">Archive</button>
<button name="intent" value="delete">Delete</button>
JS Stand-in: dispatching on the intent field

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that URLSearchParams also works as a body: forms are encoded as application/x-www-form-urlencoded unless they contain a file.

What an action can return

Return Effect
redirect("/path") navigate after success
plain data ({ ok: true }, { errors }) available as actionData in the component
data(obj, { status: 400 }) data with a status and headers
thrown Response goes to the nearest error boundary

Revalidation

After any action completes, the router calls the loaders of all active routes again, so the list page shows the new note without you touching state. You can opt out per route with shouldRevalidate, but the default is the safe one.

sequenceDiagram
  participant U as User
  participant R as Router
  participant A as action
  participant L as loaders
  U->>R: submit form (POST)
  R->>A: run action
  A-->>R: redirect or data
  R->>L: rerun active loaders
  L-->>R: fresh data
  R-->>U: updated page

One submission produces one action call and one round of loader reruns.

Always validate and authorize

An action is reachable by anyone who can send a POST, not only by your form. Check the signed-in user, validate every field, and use database parameters. The next lesson covers forms and validation in detail; the CSRF lesson covers forged cross-site posts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a route's action run?

    GET goes to the loader; mutations go to the action.
  2. 2. What does the router do after an action finishes?

    Automatic revalidation keeps the UI in sync with the data.
  3. 3. Why return redirect() after a successful POST?

    Post/redirect/get turns a refresh into a harmless GET.
  4. 4. Several buttons submit one form. How does the action tell which was pressed?

    The clicked submit button's name and value are added to the form data.

Summary

  • An action handles non-GET requests; it reads request.formData() and mutates data.
  • Return redirect() on success, data with a status for errors, or throw a Response.
  • Revalidation reruns the page's loaders automatically after each action.
  • Treat actions as public endpoints: authenticate, validate and authorize.

Next: The Form Component