diff --git a/src/components/Pages/PostDetailPage.tsx b/src/components/Pages/PostDetailPage.tsx index 06fb09e..d4e52bb 100644 --- a/src/components/Pages/PostDetailPage.tsx +++ b/src/components/Pages/PostDetailPage.tsx @@ -6,55 +6,75 @@ import { deleteDoc, doc, getDoc } from 'firebase/firestore'; import { Post } from '../../types/Posts'; import { useAuth } from '../../contexts/AuthContext'; +const fetchPost = async (id: string): Promise => { + const docRef = doc(firestore, 'posts', id); + const docSnap = await getDoc(docRef); + + if (!docSnap.exists()) { + console.log('해당 문서가 없습니다!'); + return null; + } + + const data = docSnap.data(); + return { + id: docSnap.id, + title: data.title, + content: data.content, + authorId: data.authorId, + authorName: data.authorName, + createdAt: data.createdAt?.toDate() || new Date(), + updatedAt: data.updatedAt?.toDate(), + }; +}; + +const deletePost = async (id: string): Promise => { + await deleteDoc(doc(firestore, 'posts', id)); +}; + +const handleDelete = async (id: string, navigate: NavigateFunction): Promise => { + if (!id) return; + try { + await deletePost(id); + navigate('/feed'); + } catch (error) { + console.error('게시물 삭제 오류:', error); + } +}; + const PostDetailPage: React.FC = () => { const { id } = useParams<{ id: string }>(); const [post, setPost] = useState(null); + const [isLoading, setIsLoading] = useState(true); const { currentUser } = useAuth(); const navigate = useNavigate(); - const handleDelete = async () => { - if (!id) return; - try { - await deleteDoc(doc(firestore, 'posts', id)); - navigate('/feed'); - } catch (error) { - console.error('Error deleting post:', error); - } - }; - useEffect(() => { - const fetchPost = async () => { + const loadPost = async () => { + if (!id) { + console.error('게시물 ID가 제공되지 않았습니다'); + setIsLoading(false); + return; + } + try { - if (!id) { - console.error('No post ID provided'); - return; - } - const docRef = doc(firestore, 'posts', id); - const docSnap = await getDoc(docRef); - if (docSnap.exists()) { - const data = docSnap.data(); - setPost({ - id: docSnap.id, - title: data.title, - content: data.content, - authorId: data.authorId, - authorName: data.authorName, - createdAt: data.createdAt?.toDate() || new Date(), - updatedAt: data.updatedAt?.toDate(), - }); - } else { - console.log('No such document!'); - } + const fetchedPost = await fetchPost(id); + setPost(fetchedPost); } catch (error) { - console.error('Error fetching post:', error); + console.error('게시물 가져오기 오류:', error); + } finally { + setIsLoading(false); } }; - fetchPost(); + loadPost(); }, [id]); + if (isLoading) { + return
로딩 중...
; + } + if (!post) { - return
Loading...
; + return
게시물을 찾을 수 없습니다.
; } const isAuthor = currentUser?.uid === post.authorId; @@ -69,7 +89,7 @@ const PostDetailPage: React.FC = () => { {isAuthor && (
- +
)}