|
| 1 | +import { type ActionArgs } from "@remix-run/node"; |
| 2 | +import { Form, useLoaderData } from "@remix-run/react"; |
| 3 | +import { sql } from "drizzle-orm"; |
| 4 | +import { db } from "~/db.server"; |
| 5 | +import { example } from "~/schema"; |
| 6 | + |
| 7 | +export async function action({ request }: ActionArgs) { |
| 8 | + let formData = await request.formData(); |
| 9 | + let intent = formData.get("intent"); |
| 10 | + |
| 11 | + if (intent === "update") { |
| 12 | + await db.insert(example).values({}); |
| 13 | + return new Response(null, { status: 201 }); |
| 14 | + } |
| 15 | + |
| 16 | + if (intent == "reset") { |
| 17 | + await db.delete(example); |
| 18 | + return new Response(null, { status: 204 }); |
| 19 | + } |
| 20 | + |
| 21 | + return new Response(null, { status: 400 }); |
| 22 | +} |
| 23 | + |
| 24 | +export function loader() { |
| 25 | + let result = db |
| 26 | + .select({ |
| 27 | + count: sql<number>`COUNT(*)`, |
| 28 | + lastUpdated: sql<string>`MAX(created_at)`, |
| 29 | + }) |
| 30 | + .from(example) |
| 31 | + .get(); |
| 32 | + |
| 33 | + return { |
| 34 | + count: result?.count ?? 0, |
| 35 | + lastUpdated: result?.lastUpdated ?? "never", |
| 36 | + }; |
| 37 | +} |
| 38 | + |
1 | 39 | export default function Index() {
|
| 40 | + const { count, lastUpdated } = useLoaderData<typeof loader>(); |
2 | 41 | return (
|
3 | 42 | <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
|
4 | 43 | <h1>Welcome to Remix</h1>
|
| 44 | + <p> |
| 45 | + Count: {count} <br /> |
| 46 | + Last updated: {lastUpdated} |
| 47 | + </p> |
| 48 | + <Form method="post"> |
| 49 | + <button type="submit" name="intent" value="update"> |
| 50 | + Update |
| 51 | + </button> |
| 52 | + <button type="submit" name="intent" value="reset"> |
| 53 | + Reset |
| 54 | + </button> |
| 55 | + </Form> |
5 | 56 | </div>
|
6 | 57 | );
|
7 | 58 | }
|
0 commit comments