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 / StarButton.tsx
src/components/StarButton.tsx · 72 lines · 1.7 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 StarButton({ |
| 8 | slug, |
| 9 | initialCount, |
| 10 | initialStarred, |
| 11 | isSignedIn, |
| 12 | }: { |
| 13 | slug: string; |
| 14 | initialCount: number; |
| 15 | initialStarred: boolean; |
| 16 | isSignedIn: boolean; |
| 17 | }) { |
| 18 | const router = useRouter(); |
| 19 | const [count, setCount] = useState(initialCount); |
| 20 | const [starred, setStarred] = useState(initialStarred); |
| 21 | const [pending, setPending] = useState(false); |
| 22 | |
| 23 | async function toggleStar() { |
| 24 | if (!isSignedIn) { |
| 25 | router.push(`/login?next=${encodeURIComponent(`/p/${slug}`)}`); |
| 26 | return; |
| 27 | } |
| 28 | if (pending) return; |
| 29 | |
| 30 | setPending(true); |
| 31 | const prevStarred = starred; |
| 32 | const prevCount = count; |
| 33 | setStarred(!prevStarred); |
| 34 | setCount(prevStarred ? Math.max(0, prevCount - 1) : prevCount + 1); |
| 35 | |
| 36 | try { |
| 37 | const res = await fetch(`/api/products/${encodeURIComponent(slug)}/star`, { |
| 38 | method: "POST", |
| 39 | }); |
| 40 | if (res.status === 401) { |
| 41 | router.push(`/login?next=${encodeURIComponent(`/p/${slug}`)}`); |
| 42 | return; |
| 43 | } |
| 44 | if (!res.ok) { |
| 45 | setStarred(prevStarred); |
| 46 | setCount(prevCount); |
| 47 | return; |
| 48 | } |
| 49 | const data = (await res.json()) as { starred: boolean; count: number }; |
| 50 | setStarred(data.starred); |
| 51 | setCount(data.count); |
| 52 | } catch { |
| 53 | setStarred(prevStarred); |
| 54 | setCount(prevCount); |
| 55 | } finally { |
| 56 | setPending(false); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return ( |
| 61 | <button |
| 62 | type="button" |
| 63 | className="star-btn" |
| 64 | onClick={toggleStar} |
| 65 | aria-pressed={starred} |
| 66 | disabled={pending} |
| 67 | > |
| 68 | {starred ? "★" : "☆"} {formatStarCount(count)} |
| 69 | </button> |
| 70 | ); |
| 71 | } |
| 72 |