import { useState, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { postApi } from "../api/apiService"; import { useAuth } from "../context/AuthContext"; import Layout from "../components/common/Layout"; import PostCard from "../components/post/PostCard"; import FloatingActionButton from "../components/common/FloatingActionButton"; import PostingModal from "../components/modal/PostingModal"; const ProfilePage = () => { const { user, logout } = useAuth(); const navigate = useNavigate(); const { userId: urlUserId } = useParams(); // userId가 아니라 username을 기준으로 동작하도록 변경 const username = urlUserId || (user && user.username); const isMyProfile = user && username === user.username; const [userPosts, setUserPosts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(""); const [isPostModalOpen, setIsPostModalOpen] = useState(false); useEffect(() => { if (!username) { setIsLoading(false); return; } const fetchPosts = async () => { try { setIsLoading(true); setError(""); const response = await postApi.getPosts(); // username이 일치하는 포스트만 필터링 const posts = (response.data || []).filter( (post) => post.username === username ); // 최신순 정렬 posts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); setUserPosts(posts); } catch (err) { setError("Failed to load profile information."); } finally { setIsLoading(false); } }; fetchPosts(); }, [username]); const handleLogout = () => { if (window.confirm("Are you sure you want to logout?")) { logout(); navigate("/"); } }; const togglePostModal = () => { setIsPostModalOpen(!isPostModalOpen); }; const handlePostCreated = (newPost) => { setUserPosts((prev) => [newPost, ...prev]); }; if (!username) { return ( Login is required. navigate("/")} className="px-4 py-2 text-white bg-blue-600 rounded-md hover:bg-blue-700" > Go to Home ); } if (isLoading) { return ( Loading profile information... ); } return ( {username} {isMyProfile && ( Logout )} {error && {error}} {userPosts && userPosts.length > 0 ? ( userPosts.map((post) => ) ) : ( No posts yet. )} ); }; export default ProfilePage;
Login is required.