-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
214 lines (194 loc) · 7.18 KB
/
index.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, FlatList, Image, Switch, Button, Modal, TextInput} from 'react-native';
import {registerRootComponent} from 'expo'; // higherOrder component
function App() {
const [subjects, setSubjects] = useState([]);
const [showList, setShowList] = useState(true);
const [showLoading, setShowLoading] = useState(false);
const [showModal, setShowModal] = useState(false);
const [className, setClassName] = useState('');
const [subjectName, setSubjectName] = useState('');
const [logoURL, setLogoURL] = useState('');
const [identity, setIdentity] = useState('');
const [isUpdate, setIsUpdate] = useState(false);
const API = 'https://5e5a60986a71ea0014e61d88.mockapi.io/api/subjects';
// Dinh nghia ham xu ly cong viec call API
const fetchSubjects = () => {
return fetch(
API, // api
{} // object khai bao method, header(kieu du lieu gui len, kieu du lieu nhan ve), body(data gui len)
)
.then((response) => response.json())
.then((responseJson) => {setSubjects(responseJson)})
.catch((error) => console.log(error));
};
useEffect(
// tham so 1: la 1 arrow function chua cac xu ly lien quan den API
// tham so 2: la 1 mang, chua cac item la cac bien co su thay doi,
// neu thay doi thi moi goi tiep cai ham o tham so 1
() => {
fetchSubjects();
}
, []
// Neu tham so thu 2 la array, khong co item nao thi se chi chay 1 lan
// Neu co thi se kiem tra su thay doi va neu thay doi thi goi lai arrow function
// Hien tai khi state showList thay doi thi arrow function o tren chua call lai du da render lai roi
// Gia su neu phan trang va click thi state luu page se thay doi nhung api lay du lieu trang moi van chua goi
)
// console.log(subjects, 123123, showList);
const deleteSubject = (id) => {
const newSubject = subjects.filter(item => item.id != id);
setSubjects(newSubject);
}
const handleDelete = (id) => {
setShowLoading(true);
deleteSubject(id);
fetch(
`${API}/${id}`,
{method: 'DELETE'}
).then(() => {
setShowLoading(false);
})
.catch((error) => console.log(error));
}
const setModalData = (data) => {
setClassName(data.className);
setSubjectName(data.name);
setLogoURL(data.logo);
setIdentity(data.identity);
setIsUpdate(data.id); // set isUpdate = id -> neu co id thi se hieu la true, con k co id thi se la undefined -> hieu la false
}
const handleAddSubject = (responseJson) => {
const newSubjects = [...subjects]; // clone subjects, neu clone object -> {...subject}
return newSubjects.push(responseJson); // return de gan gia tri duoi phan then
}
const handleUpdateSubject = (responseJson) => {
const newSubjects = [...subjects];
// Tim vi tri item bi thay doi
const updateSubjectIndex = newSubjects.findIndex(item => item.id = responseJson.id);
// Gan item moi cho vi tri do trong array
newSubjects[updateSubjectIndex] = responseJson;
return newSubjects;
}
const handleSubmit = () => {
// 1. Hien thi loading va an modal sau khi press submit
setShowLoading(true);
setShowModal(false);
// 2. Khai bao subject duoc them moi kem key value
const subject = {
className: className,
name: subjectName,
logo: logoURL,
identity: identity
};
// const subject = {
// className,
// name: subjectName,
// logo: logoURL,
// identity
// };
// 3. Call API de them subject vao db tren server
const api = isUpdate ? `${API}/${isUpdate}` : API;
fetch(
api,
{
method: isUpdate ? 'PUT' : 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(subject)
}
).then((response) => response.json())
.then((responseJson) => {
let newSubjects = [];
if (isUpdate) {
newSubjects = handleUpdateSubject(responseJson);
} else {
newSubjects = handleAddSubject(responseJson);
}
setSubjects(newSubjects);
setShowLoading(false);
})
.catch((error) => console.log(`ERROR: ${error}`));
setModalData({
className: '',
name: '',
logo: '',
identity: ''
});
}
const showEditModal = (id) => {
const subject = subjects.find((item) => item.id == id);
setModalData(subject);
setShowModal(true);
}
const handleCancle = () => {
setShowModal(false);
}
return (
<View style={styles.container}>
<Text>List subject</Text>
<Switch value={showList} onValueChange={() => setShowList(!showList)} />
{
showLoading
? <Text>LOADING...</Text>
: null
}
<Button title='ADD SUBJECT' onPress={() => setShowModal(true)} />
<Modal visible={showModal} >
<View>
<Text>Class Name</Text>
<TextInput value={className} onChangeText={(value) => setClassName(value)} />
</View>
<View>
<Text>Subject Name</Text>
<TextInput value={subjectName} onChangeText={(value) => setSubjectName(value)} />
</View>
<View>
<Text>Logo (Input Image URL)</Text>
<TextInput value={logoURL} onChangeText={(value) => setLogoURL(value)} />
</View>
<View>
<Text>identity</Text>
<TextInput value={identity} onChangeText={(value) => setIdentity(value)} />
</View>
<View>
<Button title='SUBMIT' onPress={() => handleSubmit()} />
<Button title='CANCLE' onPress={() => handleCancle()} />
</View>
</Modal>
{showList ? (
<FlatList
data={subjects}
renderItem={({ item }) => (
<View>
<Text>{item.id}</Text>
<Text>{item.identity}</Text>
<Text>{item.name}</Text>
<Text>{item.className}</Text>
<Image style={styles.logo} source={{ uri: item.logo }} />
<Button title='EDIT' onPress={() => showEditModal(item.id)} />
<Button title="DELETE" onPress={() => handleDelete(item.id)} />
</View>
)}
keyExtractor={(item, index) => item.id}
/>
) : null}
</View>
);
};
const styles = StyleSheet.create({
container: {
marginTop: 100,
flex: 1,
alignItems: "center",
justifyContent: 'center'
},
logo: {
width: 50,
height: 50,
borderRadius: 50
}
});
export default registerRootComponent(App);