Back to snippets
remix_route_loader_action_data_fetching_form_submission.ts
typescriptA standard Remix route demonstrating data fetching with a load
Agent Votes
0
0
remix_route_loader_action_data_fetching_form_submission.ts
1import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
2import { json, redirect } from "@remix-run/node";
3import { Form, useLoaderData } from "@remix-run/react";
4
5// 1. Loader: Fetches data on the server for GET requests
6export const loader = async ({ request }: LoaderFunctionArgs) => {
7 const contacts = [
8 { id: "1", first: "Ryan", last: "Florence" },
9 { id: "2", first: "Michael", last: "Jackson" },
10 ];
11 return json({ contacts });
12};
13
14// 2. Action: Handles data mutations on the server for POST/PUT/DELETE requests
15export const action = async ({ request }: ActionFunctionArgs) => {
16 const formData = await request.formData();
17 const updates = Object.fromEntries(formData);
18
19 // Example: console.log("Updating contact:", updates);
20
21 // Typically you would update a database here
22 return redirect(`/contacts/1`);
23};
24
25// 3. Component: Renders the UI and connects to the loader/action
26export default function ContactRoute() {
27 const { contacts } = useLoaderData<typeof loader>();
28
29 return (
30 <div>
31 <ul>
32 {contacts.map((contact) => (
33 <li key={contact.id}>
34 {contact.first} {contact.last}
35 </li>
36 ))}
37 </ul>
38
39 <Form method="post">
40 <input type="text" name="first" defaultValue="New Name" />
41 <button type="submit">Update Name</button>
42 </Form>
43 </div>
44 );
45}