diff --git a/src/app/(routes)/blog/posts/[postSlug]/comments.tsx b/src/app/(routes)/blog/posts/[postSlug]/comments.tsx new file mode 100644 index 0000000..b8da16b --- /dev/null +++ b/src/app/(routes)/blog/posts/[postSlug]/comments.tsx @@ -0,0 +1,189 @@ +"use client"; + +import { useEffect, useState } from "react"; + +type CommentItem = { + id: number; + name: string; + body: string; + created_at: string; +}; + +type CommentLabels = { + title: string; + leave: string; + name: string; + email: string; + body: string; + submit: string; + pending: string; + none: string; + error: string; +}; + +type CommentSectionProps = { + slug: string; + labels: CommentLabels; +}; + +const API_URL = process.env.NEXT_PUBLIC_BLOG_API_URL; + +export default function CommentSection({ slug, labels }: CommentSectionProps) { + const [comments, setComments] = useState([]); + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [body, setBody] = useState(""); + const [status, setStatus] = useState<"loading" | "idle" | "submitting" | "submitted" | "error">("loading"); + + useEffect(() => { + let cancelled = false; + + fetch(`${API_URL}/posts/${slug}/comments`) + .then((res) => (res.ok ? res.json() : { comments: [] })) + .then((data) => { + if (!cancelled && Array.isArray(data.comments)) { + setComments(data.comments); + setStatus("idle"); + } + }) + .catch(() => { + if (!cancelled) { + setStatus("idle"); + } + }); + + return () => { + cancelled = true; + }; + }, [slug]); + + const submit = async (event: React.FormEvent) => { + event.preventDefault(); + + setStatus("submitting"); + + try { + const res = await fetch(`${API_URL}/posts/${slug}/comments`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, email, body }), + }); + + if (res.status === 201) { + setBody(""); + setStatus("submitted"); + } else { + setStatus("error"); + } + } catch { + setStatus("error"); + } + }; + + return ( +
+

+ {labels.title} ({comments.length}) +

+ + {comments.length > 0 ? ( +
    + {comments.map((comment) => ( +
  • +
    +

    + {comment.name} +

    +

    + {formatDate(comment.created_at)} +

    +
    +

    + {comment.body} +

    +
  • + ))} +
+ ) : ( + status === "idle" && ( +

+ {labels.none} +

+ ) + )} + + {status === "submitted" ? ( +

+ {labels.pending} +

+ ) : ( +
+

+ {labels.leave} +

+ + +