'use client'; import { useState } from 'react'; import { useAuthStore } from '@/store/authStore'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { createComment } from '@/api/comments'; import { Loader2, Send } from 'lucide-react'; interface CommentFormProps { postSlug: string; parentId?: number | null; onSuccess?: () => void; // 작성 완료 후 콜백 (답글창 닫기 등) placeholder?: string; } export default function CommentForm({ postSlug, parentId = null, onSuccess, placeholder = '댓글을 남겨보세요.' }: CommentFormProps) { const { isLoggedIn } = useAuthStore(); const queryClient = useQueryClient(); const [content, setContent] = useState(''); const [guestInfo, setGuestInfo] = useState({ nickname: '', password: '' }); const mutation = useMutation({ mutationFn: createComment, onSuccess: () => { setContent(''); setGuestInfo({ nickname: '', password: '' }); queryClient.invalidateQueries({ queryKey: ['comments', postSlug] }); if (onSuccess) onSuccess(); }, onError: (error: unknown) => { const responseError = error as { response?: { data?: { message?: string; }; }; }; const fallbackMessage = error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.'; alert('댓글 작성 실패: ' + (responseError.response?.data?.message || fallbackMessage)); }, }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!content.trim()) return; if (!isLoggedIn) { if (!guestInfo.nickname.trim() || !guestInfo.password.trim()) { alert('닉네임과 비밀번호를 입력해주세요.'); return; } } mutation.mutate({ postSlug, content, parentId, guestNickname: isLoggedIn ? undefined : guestInfo.nickname, guestPassword: isLoggedIn ? undefined : guestInfo.password, }); }; return (
{/* 비회원 입력 필드 */} {!isLoggedIn && (
setGuestInfo({ ...guestInfo, nickname: e.target.value })} className="w-1/2 rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 py-2 text-sm text-[var(--color-text)] outline-none transition focus:border-[var(--color-accent)]" required /> setGuestInfo({ ...guestInfo, password: e.target.value })} className="w-1/2 rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 py-2 text-sm text-[var(--color-text)] outline-none transition focus:border-[var(--color-accent)]" required />
)} {/* 댓글 내용 입력 */}