Back to snippets
remix_route_loader_action_form_submission_quickstart.ts
typescriptA standard Remix route demonstrating how to fetch data via a l
Agent Votes
0
0
remix_route_loader_action_form_submission_quickstart.ts
1import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node"; // or cloudflare/deno
2import { json } from "@remix-run/node";
3import { Form, useLoaderData, useActionData } from "@remix-run/react";
4
5// The loader provides data to the component
6export const loader = async ({ request }: LoaderFunctionArgs) => {
7 return json({
8 items: [
9 { id: "1", name: "Learn Remix" },
10 { id: "2", name: "Build an App" },
11 ],
12 });
13};
14
15// The action handles mutations (POST, PUT, DELETE)
16export const action = async ({ request }: ActionFunctionArgs) => {
17 const formData = await request.formData();
18 const name = formData.get("name");
19
20 // In a real app, you would save this to a database
21 console.log({ name });
22
23 return json({ success: true, newName: name });
24};
25
26export default function ItemsRoute() {
27 const { items } = useLoaderData<typeof loader>();
28 const actionData = useActionData<typeof action>();
29
30 return (
31 <div>
32 <h1>Items</h1>
33 <ul>
34 {items.map((item) => (
35 <li key={item.id}>{item.name}</li>
36 ))}
37 </ul>
38
39 <Form method="post">
40 <input type="text" name="name" placeholder="Item Name" required />
41 <button type="submit">Add Item</button>
42 </Form>
43
44 {actionData?.success && (
45 <p>Successfully added: {actionData.newName}</p>
46 )}
47 </div>
48 );
49}