cg / hackerproducts
63 files · 5,740 lines · 159.1 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.
Quick jump: page.tsxpage.tsxglobals.cssschema.sqlpackage.json
root / src / components / UpvoteButton.tsx
src/components/UpvoteButton.tsx · 79 lines · 1.9 KB← back to folder
| 1 | "use client"; |
| 2 | |
| 3 | import { useState } from "react"; |
| 4 | import { useRouter } from "next/navigation"; |
| 5 | import { formatStarCount } from "@/lib/format"; |
| 6 | |
| 7 | export function UpvoteButton({ |
| 8 | slug, |
| 9 | initialCount, |
| 10 | initialUpvoted, |
| 11 | isSignedIn, |
| 12 | variant = "button", |
| 13 | returnTo, |
| 14 | }: { |
| 15 | slug: string; |
| 16 | initialCount: number; |
| 17 | initialUpvoted: boolean; |
| 18 | isSignedIn: boolean; |
| 19 | variant?: "button" | "inline"; |
| 20 | returnTo?: string; |
| 21 | }) { |
| 22 | const router = useRouter(); |
| 23 | const [count, setCount] = useState(initialCount); |
| 24 | const [upvoted, setUpvoted] = useState(initialUpvoted); |
| 25 | const [pending, setPending] = useState(false); |
| 26 | |
| 27 | async function toggleUpvote() { |
| 28 | const nextPath = returnTo ?? `/${slug}`; |
| 29 | if (!isSignedIn) { |
| 30 | router.push(`/login?next=${encodeURIComponent(nextPath)}`); |
| 31 | return; |
| 32 | } |
| 33 | if (pending) return; |
| 34 | |
| 35 | setPending(true); |
| 36 | const prevUpvoted = upvoted; |
| 37 | const prevCount = count; |
| 38 | setUpvoted(!prevUpvoted); |
| 39 | setCount(prevUpvoted ? Math.max(0, prevCount - 1) : prevCount + 1); |
| 40 | |
| 41 | try { |
| 42 | const res = await fetch(`/api/products/${encodeURIComponent(slug)}/upvote`, { |
| 43 | method: "POST", |
| 44 | }); |
| 45 | if (res.status === 401) { |
| 46 | router.push(`/login?next=${encodeURIComponent(nextPath)}`); |
| 47 | return; |
| 48 | } |
| 49 | if (!res.ok) { |
| 50 | setUpvoted(prevUpvoted); |
| 51 | setCount(prevCount); |
| 52 | return; |
| 53 | } |
| 54 | const data = (await res.json()) as { upvoted: boolean; count: number }; |
| 55 | setUpvoted(data.upvoted); |
| 56 | setCount(data.count); |
| 57 | } catch { |
| 58 | setUpvoted(prevUpvoted); |
| 59 | setCount(prevCount); |
| 60 | } finally { |
| 61 | setPending(false); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return ( |
| 66 | <button |
| 67 | type="button" |
| 68 | className={variant === "inline" ? "upvote-inline" : "star-btn"} |
| 69 | onClick={toggleUpvote} |
| 70 | aria-pressed={upvoted} |
| 71 | disabled={pending} |
| 72 | title={upvoted ? "Remove upvote" : "Upvote"} |
| 73 | data-ml-goal="upvote_click" |
| 74 | > |
| 75 | {upvoted ? "▲" : "△"} {formatStarCount(count)} |
| 76 | </button> |
| 77 | ); |
| 78 | } |
| 79 |