-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathstore.ts
82 lines (77 loc) · 2.02 KB
/
store.ts
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
import { create } from "zustand";
type Todo = {
id: number;
title: string;
completed: boolean;
};
type CreateTodo = {
title: string;
};
type TodoStore = {
todos: Todo[];
fetchTodos: () => void;
addTodo: (todo: CreateTodo) => void;
updateTodo: (updatedTodo: Todo) => void;
deleteTodo: (id: number) => void;
};
const URL = process.env.NEXT_PUBLIC_VERCEL_URL
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}/api`
: "http://localhost:3000/api";
export const useStore = create<TodoStore>((set) => ({
todos: [],
fetchTodos: async () => {
try {
const response = await fetch(`${URL}/todos`);
const todos = await response.json();
set({ todos });
} catch (error) {
console.error("Error fetching todos:", error);
}
},
addTodo: async (todo) => {
try {
const response = await fetch(`${URL}/todos`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
});
const createdTodo = await response.json();
set((state) => ({ todos: [...state.todos, createdTodo] }));
} catch (error) {
console.error("Error creating todo:", error);
}
},
updateTodo: async (updatedTodo) => {
try {
const response = await fetch(`${URL}/todos/${updatedTodo.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedTodo),
});
const updatedItem = await response.json();
set((state) => ({
todos: state.todos.map((todo) =>
todo.id === updatedItem.id ? updatedItem : todo
),
}));
} catch (error) {
console.error("Error updating todo:", error);
}
},
deleteTodo: async (id) => {
try {
await fetch(`${URL}/todos/${id}`, {
method: "DELETE",
});
set((state) => ({
todos: state.todos.filter((todo) => todo.id !== id),
}));
} catch (error) {
console.error("Error deleting todo:", error);
}
},
}));