action

Watch the 📼 Remix Singles: Data Mutations with Form + action and Multiple Forms and Single Button Mutations

Like loader, action is a server-only function to handle data mutations and other actions. If a non-GET request is made to your route (POST, PUT, PATCH, DELETE) then the action is called before the loaders.

Actions have the same API as loaders, the only difference is when they are called.

This enables you to co-locate everything about a data set in a single route module: the data read, the component that renders the data, and the data writes:

  1. import type { ActionArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { json, redirect } from "@remix-run/node"; // or cloudflare/deno
  3. import { Form } from "@remix-run/react";
  4. import { TodoList } from "~/components/TodoList";
  5. import { fakeCreateTodo, fakeGetTodos } from "~/utils/db";
  6. export async function loader() {
  7. return json(await fakeGetTodos());
  8. }
  9. export async function action({ request }: ActionArgs) {
  10. const body = await request.formData();
  11. const todo = await fakeCreateTodo({
  12. title: body.get("title"),
  13. });
  14. return redirect(`/todos/${todo.id}`);
  15. }
  16. export default function Todos() {
  17. const data = useLoaderData<typeof loader>();
  18. return (
  19. <div>
  20. <TodoList todos={data} />
  21. <Form method="post">
  22. <input type="text" name="title" />
  23. <button type="submit">Create Todo</button>
  24. </Form>
  25. </div>
  26. );
  27. }

When a POST is made to a URL, multiple routes in your route hierarchy will match the URL. Unlike a GET to loaders, where all of them are called to build the UI, only one action is called.

The route called will be the deepest matching route, unless the deepest matching route is an “index route”. In this case, it will post to the parent route of the index (because they share the same URL, the parent wins).

If you want to post to an index route use ?index in the action: <Form action="/accounts?index" method="post" />

action urlroute action
/accounts?indexroutes/accounts/index.js
/accountsroutes/accounts.js

Also note that forms without an action prop (<Form method="post">) will automatically post to the same route within which they are rendered, so using the ?index param to disambiguate between parent and index routes is only useful if you’re posting to an index route from somewhere besides the index route itself. If you’re posting from the index route to itself, or from the parent route to itself, you don’t need to define a <Form action> at all, just omit it: <Form method="post">.

See also: