"use client"; import { useState } from "react"; export function UpvoteButton({ ideaId, initialCount, initialHasVoted, }: { ideaId: string; initialCount: number; initialHasVoted: boolean; }) { const [count, setCount] = useState(initialCount); const [hasVoted, setHasVoted] = useState(initialHasVoted); const [isPending, setIsPending] = useState(false); async function handleVote(e: React.MouseEvent) { e.preventDefault(); e.stopPropagation(); if (isPending) return; setIsPending(true); const newVoted = !hasVoted; setHasVoted(newVoted); setCount((c) => (newVoted ? c + 1 : c - 1)); try { const res = await fetch(`/api/ideas/${ideaId}/upvote`, { method: newVoted ? "POST" : "DELETE", }); if (!res.ok) { setHasVoted(!newVoted); setCount((c) => (newVoted ? c - 1 : c + 1)); } } catch { setHasVoted(!newVoted); setCount((c) => (newVoted ? c - 1 : c + 1)); } finally { setIsPending(false); } } return ( ); }