-
Notifications
You must be signed in to change notification settings - Fork 454
/
Copy pathFeedbackContext.js
98 lines (81 loc) · 2.26 KB
/
FeedbackContext.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
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
import { createContext, useState, useEffect } from 'react'
const FeedbackContext = createContext()
export const FeedbackProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(true)
const [feedback, setFeedback] = useState([])
const [feedbackEdit, setFeedbackEdit] = useState({
item: {},
edit: false,
})
useEffect(() => {
fetchFeedback()
}, [])
// Fetch feedback
const fetchFeedback = async () => {
const response = await fetch(`/feedback?_sort=id&_order=desc`)
const data = await response.json()
setFeedback(data)
setIsLoading(false)
}
// Add feedback
const addFeedback = async (newFeedback) => {
const response = await fetch('/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newFeedback),
})
const data = await response.json()
setFeedback([data, ...feedback])
}
// Delete feedback
const deleteFeedback = async (id) => {
if (window.confirm('Are you sure you want to delete?')) {
await fetch(`/feedback/${id}`, { method: 'DELETE' })
setFeedback(feedback.filter((item) => item.id !== id))
}
}
// Update feedback item
const updateFeedback = async (id, updItem) => {
const response = await fetch(`/feedback/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updItem),
})
const data = await response.json()
// NOTE: no need to spread data and item
setFeedback(feedback.map((item) => (item.id === id ? data : item)))
// FIX: this fixes being able to add a feedback after editing
// credit to Jose https://www.udemy.com/course/react-front-to-back-2022/learn/lecture/29768200#questions/16462688
setFeedbackEdit({
item: {},
edit: false,
})
}
// Set item to be updated
const editFeedback = (item) => {
setFeedbackEdit({
item,
edit: true,
})
}
return (
<FeedbackContext.Provider
value={{
feedback,
feedbackEdit,
isLoading,
deleteFeedback,
addFeedback,
editFeedback,
updateFeedback,
}}
>
{children}
</FeedbackContext.Provider>
)
}
export default FeedbackContext