-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
114 lines (104 loc) · 2.81 KB
/
Copy pathApp.tsx
File metadata and controls
114 lines (104 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { useState } from "react";
import "./App.css";
import TaskInputBox from "./components/TaskInputBox";
import TodoItem from "./components/TodoItem";
function reportError(message: string, e: unknown) {
console.error(`${message}\n${e}`);
if (e instanceof Error) {
console.error(e.stack);
}
}
export type TaskId = string;
export class Task {
constructor(
public name: string,
public isCompleted: boolean,
public id: TaskId
) {}
}
export type TaskMap = Record<TaskId, Task>;
function App(props: { initialTasks: TaskMap }) {
const [tasks, setTasks] = useState<TaskMap>(props.initialTasks);
const taskElementList = Object.entries(tasks).map(([id, task]) => (
<TodoItem
key={id}
task={task}
deleteTask={deleteTask}
markTaskCompleted={setTaskComplete}
editTask={editTask}
/>
));
async function deleteTask(id: TaskId) {
try {
const resp = await fetch(`http://localhost:8000/tasks/${id}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
});
if (resp.ok) {
const newTasks = { ...tasks };
delete newTasks[id];
setTasks(newTasks);
}
} catch (e) {
reportError("Failed to delete", e);
}
}
async function updateTask(
id: TaskId,
edits: { isCompleted?: boolean; name?: string }
) {
try {
const task = tasks[id];
if (!task) {
return;
}
const isCompleted = edits.isCompleted ?? task.isCompleted;
const name = edits.name ?? task.name;
const resp = await fetch(`http://localhost:8000/tasks/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
isCompleted,
}),
});
if (resp.ok) {
const newTask = (await resp.json()) as Task;
const newTasks = { ...tasks, [id]: newTask };
setTasks(newTasks);
}
} catch (e) {
reportError(`Failed to update task`, e);
}
}
function setTaskComplete(id: TaskId) {
updateTask(id, { isCompleted: true });
}
function editTask(id: TaskId, name: string) {
updateTask(id, { name });
}
async function addTask(name: string) {
try {
const resp = await fetch("http://localhost:8000/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name, isCompleted: false }),
});
if (resp.ok) {
const newTask = (await resp.json()) as Task;
const newTasks = { ...tasks, [newTask.id]: newTask };
setTasks(newTasks);
}
} catch (e) {
reportError("Failed to create task", e);
}
}
return (
<>
<h1>To Do List</h1>
<TaskInputBox addTask={addTask} />
{taskElementList}
</>
);
}
export default App;