import { useState } from 'react'; import type { FormEvent } from 'react'; import { format } from 'date-fns'; import { getComments, postComment } from '../api'; import { useAsync } from '../lib/useAsync'; export default function CommentSection({ postId }: { postId: string }) { const [reloadKey, setReloadKey] = useState(0); const { data: comments, loading } = useAsync(() => getComments(postId), [postId, reloadKey]); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [comment, setComment] = useState(''); const [state, setState] = useState<'idle' | 'busy' | 'error'>('idle'); async function onSubmit(e: FormEvent) { e.preventDefault(); if (!name.trim() || !email.trim() || !comment.trim()) return; setState('busy'); try { await postComment({ postId, name: name.trim(), email: email.trim(), comment: comment.trim() }); setName(''); setEmail(''); setComment(''); setState('idle'); setReloadKey((k) => k + 1); } catch { setState('error'); } } const list = comments ?? []; return (

{list.length === 1 ? '1 Comment' : `${list.length} Comments`}

{loading &&

Loading comments…

}

Leave a comment

setName(e.target.value)} required /> setEmail(e.target.value)} required />