import React, { useState, useEffect } from 'react'; import Button from './Button'; import { getComments, createComment } from '../services/api'; const CommentSection = ({ postId, userName }) => { const [comments, setComments] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const [newComment, setNewComment] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); // 댓글 목록 불러오기 const fetchComments = async () => { setIsLoading(true); setError(''); try { const fetchedComments = await getComments(postId); setComments(fetchedComments); } catch (err) { console.error('댓글 불러오기 오류:', err); setError('댓글을 불러오는데 실패했습니다.'); } finally { setIsLoading(false); } }; // 컴포넌트 마운트 시 댓글 불러오기 useEffect(() => { fetchComments(); }, [postId]); // 새 댓글 작성 처리 const handleSubmitComment = async (e) => { e.preventDefault(); if (!newComment.trim()) return; setIsSubmitting(true); try { const commentData = { userName, content: newComment }; const createdComment = await createComment(postId, commentData); setComments([...comments, createdComment]); setNewComment(''); } catch (err) { console.error('댓글 작성 오류:', err); setError('댓글 작성에 실패했습니다.'); } finally { setIsSubmitting(false); } }; // 날짜 포맷팅 const formatDate = (dateString) => { const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }; return new Date(dateString).toLocaleDateString('ko-KR', options); }; return (
{error}
} {isLoading ? (댓글 불러오는 중...
) : (아직 댓글이 없습니다.
) : ( comments.map(comment => ({comment.content}