Remix Utils - v9.3.1
    Preparing search index...

    Module Server/Named Action

    Note

    Install using bunx shadcn@latest add @remix-utils/named-action.

    Note

    This depends on React Router.

    It's common to need to handle more than one action in the same route, there are many options here like sending the form to a resource route or using an action reducer, the namedAction function uses some conventions to implement the action reducer pattern.

    import { namedAction } from "remix-utils/named-action";

    export async function action({ request }: Route.ActionArgs) {
    return namedAction(await request.formData(), {
    async create() {
    // do create
    },
    async update() {
    // do update
    },
    async delete() {
    // do delete
    },
    });
    }

    export default function Component() {
    return (
    <>
    <Form method="post">
    <input type="hidden" name="intent" value="create" />
    ...
    </Form>

    <Form method="post">
    <input type="hidden" name="intent" value="update" />
    ...
    </Form>

    <Form method="post">
    <input type="hidden" name="intent" value="delete" />
    ...
    </Form>
    </>
    );
    }

    This function can follow this convention:

    You can pass a FormData object to the namedAction, then it will try to find a field named intent and use the value as the action name.

    If, in any case, the action name is not found, the actionName then the library will try to call an action named default, similar to a switch in JavaScript.

    If the default is not defined it will throw a ReferenceError with the message Action "${name}" not found.

    If the library couldn't found the name at all, it will throw a ReferenceError with the message Action name not found

    Functions

    namedAction