-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChildCareDetail.js
448 lines (412 loc) · 11.7 KB
/
ChildCareDetail.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import React, { useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
ScrollView,
TouchableOpacity,
TextInput,
Alert,
ActivityIndicator,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Icon from "react-native-vector-icons/MaterialIcons";
const ChildCareDetail = ({ route, navigation }) => {
const { postId } = route.params;
const [post, setPost] = useState(null);
const [loading, setLoading] = useState(true);
const [newComment, setNewComment] = useState("");
const [comments, setComments] = useState([]);
const [userNickname, setUserNickname] = useState(null);
useEffect(() => {
loadPostDetail();
loadComments();
const getUserNickname = async () => {
const nickname = await AsyncStorage.getItem("userNickname");
setUserNickname(nickname);
};
getUserNickname();
}, [postId]);
const loadPostDetail = async () => {
try {
const jwtToken = await AsyncStorage.getItem("jwtToken");
if (!jwtToken) {
Alert.alert("인증 오류", "로그인이 필요합니다.");
navigation.navigate("KakaoLogin");
return;
}
const response = await fetch(
`http://192.168.61.45:8080/api/carePosts/${postId}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
if (response.status === 401) {
Alert.alert("인증 만료", "다시 로그인해주세요.");
navigation.navigate("KakaoLogin");
return;
}
throw new Error("게시글을 불러오는데 실패했습니다.");
}
const data = await response.json();
setPost(data);
setComments(data.comments || []);
} catch (error) {
console.error("게시글 상세 정보 로딩 에러:", error);
Alert.alert("오류", "게시글을 불러오는데 실패했습니다.");
} finally {
setLoading(false);
}
};
const loadComments = async () => {
try {
const jwtToken = await AsyncStorage.getItem("jwtToken");
const carePostId = route.params.postId;
const response = await fetch(
`http://192.168.61.45:8080/api/carePosts/${carePostId}/comments`,
{
method: "GET",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
throw new Error("댓글을 불러오는데 실패했습니다.");
}
const data = await response.json();
console.log("받아온 댓글 데이터:", data);
setComments(data);
} catch (error) {
console.error("댓글 로딩 에러:", error);
Alert.alert("오류", "댓글을 불러오는데 실패했습니다.");
}
};
const handleAddComment = async () => {
if (!newComment.trim()) {
Alert.alert("알림", "댓글 내용을 입력해주세요.");
return;
}
try {
const jwtToken = await AsyncStorage.getItem("jwtToken");
const carePostId = route.params.postId;
const response = await fetch(
`http://192.168.61.45:8080/api/carePosts/${carePostId}/comments`,
{
method: "POST",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
content: newComment.trim(),
postId: carePostId,
}),
}
);
if (!response.ok) {
if (response.status === 401) {
Alert.alert("인증 만료", "다시 로그인해주세요.");
navigation.navigate("KakaoLogin");
return;
}
throw new Error("댓글 작성에 실패했습니다.");
}
setNewComment("");
loadComments();
Alert.alert("성공", "댓글이 등록되었습니다.");
} catch (error) {
console.error("댓글 작성 에러:", error);
Alert.alert("오류", "댓글 작성에 실패했습니다.");
}
};
const handleDeleteComment = async (careCommentId) => {
if (!careCommentId) {
console.error("댓글 ID가 없습니다.");
Alert.alert("오류", "댓글을 삭제할 수 없습니다.");
return;
}
try {
const jwtToken = await AsyncStorage.getItem("jwtToken");
const carePostId = route.params.postId;
if (!jwtToken) {
Alert.alert("인증 오류", "로그인이 필요합니다.");
navigation.navigate("KakaoLogin");
return;
}
Alert.alert("댓글 삭제", "정말로 이 댓글을 삭제하시겠습니까?", [
{
text: "취소",
style: "cancel",
},
{
text: "삭제",
onPress: async () => {
try {
console.log(
`댓글 삭제 시도 - CarePostId: ${carePostId}, CareCommentId: ${careCommentId}`
);
const response = await fetch(
`http://192.168.61.45:8080/api/carePosts/${carePostId}/comments/${careCommentId}`,
{
method: "DELETE",
headers: {
Authorization: `Bearer ${jwtToken}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
const errorData = await response.text();
throw new Error(errorData);
}
Alert.alert("성공", "댓글이 삭제되었습니다.");
await loadComments();
} catch (error) {
console.error("댓글 삭제 처리 중 에러:", error);
Alert.alert("오류", "댓글 삭제에 실패했습니다.");
}
},
style: "destructive",
},
]);
} catch (error) {
console.error("댓글 삭제 함수 에러:", error);
Alert.alert("오류", "댓글 삭제 처리 중 오류가 발생했습니다.");
}
};
const renderComments = () => (
<View style={styles.commentsSection}>
<Text style={styles.commentHeader}>댓글 {comments.length}개</Text>
{comments.map((comment) => {
console.log("댓글 정보:", comment);
return (
<View key={comment.careCommentId} style={styles.commentItem}>
<View style={styles.commentHeader}>
<View style={styles.commentAuthorContainer}>
<Text style={styles.commentAuthor}>{comment.nickname}</Text>
<Text style={styles.commentDate}>
{formatDate(comment.updatedAt)}
</Text>
</View>
{userNickname === comment.nickname && (
<TouchableOpacity
onPress={() => {
console.log("삭제하려는 댓글 ID:", comment.careCommentId);
handleDeleteComment(comment.careCommentId);
}}
style={styles.deleteButton}
>
<Icon name="delete-outline" size={20} color="#666" />
</TouchableOpacity>
)}
</View>
<Text style={styles.commentContent}>{comment.content}</Text>
</View>
);
})}
</View>
);
// 날짜 포맷팅 함수 추가
const formatDate = (dateString) => {
if (!dateString) return "";
const date = new Date(dateString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${year}.${month}.${day} ${hours}:${minutes}`;
};
if (loading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#FFEDAE" />
</View>
);
}
if (!post) {
return (
<View style={styles.container}>
<Text>게시글을 찾을 수 없습니다.</Text>
</View>
);
}
return (
<View style={styles.container}>
<ScrollView style={styles.content}>
<View style={styles.tagContainer}>
{post.tags?.map((tag, index) => (
<Text key={index} style={styles.tag}>
#{tag}
</Text>
))}
</View>
<Text style={styles.title}>{post.title}</Text>
<Text style={styles.postContent}>{post.content}</Text>
<View style={styles.authorInfo}>
<Text style={styles.author}>{post.nickname}</Text>
<Text style={styles.date}>
{post.updatedAt ? formatDate(post.updatedAt) : "날짜 없음"}
</Text>
</View>
<View style={styles.divider} />
{renderComments()}
</ScrollView>
<View style={styles.commentInputContainer}>
<TextInput
style={styles.commentInput}
value={newComment}
onChangeText={setNewComment}
placeholder="댓글을 입력하세요"
multiline
maxLength={500}
/>
<TouchableOpacity
style={styles.commentSubmitButton}
onPress={handleAddComment}
>
<Text style={styles.commentSubmitText}>등록</Text>
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
content: {
flex: 1,
padding: 16,
},
tagContainer: {
flexDirection: "row",
flexWrap: "wrap",
marginBottom: 12,
},
tag: {
backgroundColor: "#FFEDAE",
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 15,
marginRight: 8,
marginBottom: 8,
fontSize: 14,
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 16,
},
authorInfo: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 20,
paddingHorizontal: 4,
},
author: {
fontSize: 14,
color: "#333",
fontWeight: "bold",
},
date: {
fontSize: 12,
color: "#666",
},
postContent: {
fontSize: 16,
lineHeight: 24,
color: "#333",
marginBottom: 20,
},
divider: {
height: 1,
backgroundColor: "#eee",
marginVertical: 20,
},
commentsSection: {
marginTop: 20,
paddingHorizontal: 16,
},
commentHeader: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 4,
},
commentAuthorContainer: {
flex: 1,
},
deleteButton: {
padding: 4,
},
commentItem: {
backgroundColor: "#f8f8f8",
padding: 12,
borderRadius: 8,
marginBottom: 8,
},
commentAuthor: {
fontSize: 14,
fontWeight: "bold",
color: "#333",
},
commentDate: {
fontSize: 12,
color: "#666",
marginTop: 2,
},
commentContent: {
fontSize: 14,
color: "#333",
lineHeight: 20,
marginTop: 4,
},
commentInputContainer: {
padding: 16,
backgroundColor: "#fff",
borderTopWidth: 1,
borderTopColor: "#eee",
flexDirection: "row",
alignItems: "center",
},
commentInput: {
flex: 1,
borderWidth: 1,
borderColor: "#FFEDAE",
borderRadius: 20,
paddingHorizontal: 16,
paddingVertical: 8,
marginRight: 8,
maxHeight: 100,
fontSize: 14,
},
commentSubmitButton: {
backgroundColor: "#FFEDAE",
paddingHorizontal: 16,
paddingVertical: 8,
borderRadius: 20,
justifyContent: "center",
alignItems: "center",
},
commentSubmitText: {
color: "#333",
fontWeight: "bold",
fontSize: 14,
},
});
export default ChildCareDetail;