|
| 1 | +import ArticleContent from "@/components/board/ArticleContent"; |
| 2 | +import { Article } from "@/types/Types"; |
| 3 | +import Link from "next/link"; |
| 4 | +import { useRouter } from "next/router"; |
| 5 | +import { useEffect, useState } from "react"; |
| 6 | +import { getArticleDetail } from "@/api/api"; |
| 7 | + |
| 8 | +const Board = () => { |
| 9 | + const router = useRouter(); |
| 10 | + const { id } = router.query; |
| 11 | + |
| 12 | + const [article, setArticle] = useState<Article | null>(null); |
| 13 | + const [error, setError] = useState<string | null>(null); |
| 14 | + const [loading, setLoading] = useState<boolean>(true); // 로딩 상태 추가 |
| 15 | + |
| 16 | + // URL에서 가져온 id 값은 문자열로 되어 있을 수 있기 때문에, 이를 Number()를 사용하여 숫자로 변환 |
| 17 | + const articleId = Number(id); |
| 18 | + |
| 19 | + // 데이터 로딩 |
| 20 | + useEffect(() => { |
| 21 | + const fetchArticle = async () => { |
| 22 | + if (!articleId) return; // If there's no articleId, exit early |
| 23 | + |
| 24 | + try { |
| 25 | + setLoading(true); |
| 26 | + setError(null); |
| 27 | + const data = await getArticleDetail(articleId); // Make API call |
| 28 | + setArticle(data); |
| 29 | + } catch (err) { |
| 30 | + console.error("오류:", err); |
| 31 | + setError("실패"); |
| 32 | + } finally { |
| 33 | + setLoading(false); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + fetchArticle(); |
| 38 | + }, [articleId]); |
| 39 | + |
| 40 | + // 로딩 중이나 에러가 발생한 경우 |
| 41 | + if (loading) return <div>로딩 중...</div>; |
| 42 | + if (error) return <div>에러: {error}</div>; |
| 43 | + |
| 44 | + // id가 없거나 article 데이터가 로드되지 않았다면 null을 반환 |
| 45 | + if (!id || !article) return null; |
| 46 | + |
| 47 | + return ( |
| 48 | + <div> |
| 49 | + <ArticleContent article={article} /> |
| 50 | + |
| 51 | + {/* 댓글 컴포넌트 */} |
| 52 | + |
| 53 | + <Link href="/board"> |
| 54 | + <button className="backButton">목록으로 돌아가기</button> |
| 55 | + </Link> |
| 56 | + </div> |
| 57 | + ); |
| 58 | +}; |
| 59 | + |
| 60 | +export default Board; |
0 commit comments