-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
100 lines (79 loc) · 2.37 KB
/
Copy pathApp.js
File metadata and controls
100 lines (79 loc) · 2.37 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
import { useState, useEffect } from 'react'
import Header from './components/Header'
import Footer from './components/Footer'
import Tasks from './components/Tasks'
import AddTask from './components/AddTask'
import About from './components/About'
function App() {
const [showAddTask, setShowAddTask] = useState(false)
const [tasks, setTasks] = useState([])
useEffect(() => {
const getTasks = async () => {
const tasksFromServer = await fetchTasks()
setTasks(tasksFromServer)
}
getTasks()
}, [])
// Fetch Tasks
const fetchTasks = async () => {
const res = await fetch('http://localhost:5000/tasks')
const data = await res.json()
return data
}
// Fetch Task
const fetchTask = async (id) => {
const res = await fetch(`http://localhost:5000/tasks/${id}`)
const data = await res.json()
return data
}
// Add Task
const addTask = async (task) => {
const res = await fetch('http://localhost:5000/tasks', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(task)
})
const data = await res.json()
setTasks([...tasks, data])
//const id = Math.floor(Math.random() * 10000) + 1
//const newTask = { id, ...task }
//setTasks([...tasks, newTask])
}
// Delete Task
const deleteTask = async (id) => {
await fetch(`http://localhost:5000/tasks/${id}`, {
method: 'DELETE'
})
setTasks(tasks.filter((task) => task.id !== id))
}
// Toggle Reminder
const toggleReminder = async (id) => {
const taskToToggle = await fetchTask(id)
const updTask = { ...taskToToggle, reminder: !taskToToggle.reminder}
const res = await fetch(`http://localhost:5000/tasks/${id}`, {
method: 'PUT',
headers: {
'Content-type':'application/json',
},
body: JSON.stringify(updTask),
})
const data = await res.json()
setTasks(tasks.map((task) => task.id === id ? { ...task, reminder:
data.reminder} : task
)
)
}
return (
<div className='container'>
<Header onAdd={() => setShowAddTask(!showAddTask)} showAdd={showAddTask}/>
{showAddTask && <AddTask onAdd={addTask}/>}
{tasks.length > 0 ? <Tasks tasks={tasks}
onDelete={deleteTask}
onToggle={toggleReminder}/> : ('No Tasks to Show')}
<Footer />
</div>
);
}
export default App;