-
Notifications
You must be signed in to change notification settings - Fork 0
/
useTasks.js
58 lines (50 loc) · 1.46 KB
/
useTasks.js
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
import { useReducer, useEffect } from "react";
function getTasks(options) {
return fetch("/tasks", options).then((res) => res.json());
}
function updateTask(tasks, id, updatedTask) {
return tasks.map((task) =>
task.id === id ? { ...task, ...updatedTask } : task
);
}
function deleteTask(tasks, id) {
return tasks.filter((task) => task.id !== id);
}
export const reducer = (tasks, action) => {
switch (action.type) {
case "UPDATE_TASKS":
return action.tasks;
case "ARCHIVE_TASK":
return updateTask(tasks, action.id, { state: "TASK_ARCHIVED" });
case "PIN_TASK":
return updateTask(tasks, action.id, { state: "TASK_PINNED" });
case "INBOX_TASK":
return updateTask(tasks, action.id, { state: "TASK_INBOX" });
case "DELETE_TASK":
return deleteTask(tasks, action.id);
case "EDIT_TITLE":
return updateTask(tasks, action.id, { title: action.title });
default:
return tasks;
}
};
export function useTasks() {
const [tasks, dispatch] = useReducer(reducer, []);
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
getTasks({ signal })
.then(({ tasks }) => {
dispatch({ type: "UPDATE_TASKS", tasks });
})
.catch((error) => {
if (!abortController.signal.aborted) {
console.log(error);
}
});
return () => {
abortController.abort();
};
}, []);
return [tasks, dispatch];
}