Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use client";
- import { useEffect, useState } from "react";
- type Task = { userId: string; taskId: string; title: string; done: boolean; createdAt: string };
- export default function Home() {
- const [userId, setUserId] = useState("alice");
- const [tasks, setTasks] = useState<Task[]>([]);
- const [title, setTitle] = useState("");
- const [version, setVersion] = useState(0); // bump to reload the list
- const reload = () => setVersion((v) => v + 1);
- // Load the user's tasks whenever the user changes or after any write
- useEffect(() => {
- let cancelled = false;
- fetch(`/api/tasks?userId=${encodeURIComponent(userId)}`)
- .then((res) => res.json())
- .then((data) => !cancelled && setTasks(data));
- return () => {
- cancelled = true;
- };
- }, [userId, version]);
- async function addTask(e: React.FormEvent) {
- e.preventDefault();
- if (!title.trim()) return;
- await fetch("/api/tasks", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ userId, title }),
- });
- setTitle("");
- reload();
- }
- async function toggle(t: Task) {
- await fetch(`/api/tasks/${t.taskId}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ userId, done: !t.done }),
- });
- reload();
- }
- async function remove(t: Task) {
- await fetch(`/api/tasks/t.taskId?userId={encodeURIComponent(userId)}`, { method: "DELETE" });
- reload();
- }
- return (
- <main style={{ maxWidth: 560, margin: "40px auto", fontFamily: "system-ui", padding: "0 16px" }}>
- <h1>Task App (DynamoDB)</h1>
- <label>
- User:{" "}
- <select value={userId} onChange={(e) => setUserId(e.target.value)}>
- <option>alice</option>
- <option>bob</option>
- </select>
- </label>
- <form onSubmit={addTask} style={{ display: "flex", gap: 8, margin: "16px 0" }}>
- <input
- value={title}
- onChange={(e) => setTitle(e.target.value)}
- placeholder="New task"
- style={{ flex: 1, padding: 8 }}
- />
- <button>Add</button>
- </form>
- <ul style={{ listStyle: "none", padding: 0 }}>
- {tasks.map((t) => (
- <li key={t.taskId} style={{ display: "flex", gap: 8, padding: "8px 0", borderBottom: "1px solid #ddd" }}>
- <input type="checkbox" checked={t.done} onChange={() => toggle(t)} />
- <span style={{ flex: 1, textDecoration: t.done ? "line-through" : "none" }}>{t.title}</span>
- <button onClick={() => remove(t)}>Delete</button>
- </li>
- ))}
- </ul>
- <p>{tasks.length} task(s) for {userId}</p>
- </main>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment