// components/GitHubStarsButton.tsx "use client"; import React, { useEffect, useState } from "react"; import Link from "next/link"; import { cn, nFormatter } from "@/lib/utils"; import { buttonVariants } from "../ui/button"; interface GitHubStarsButtonProps { owner: string; repo: string; className?: string; initialStars?: number; } const GitHubStarsButton: React.FC = ({ owner, repo, className = "", initialStars, }) => { const [stars, setStars] = useState(initialStars ?? 0); const [loading, setLoading] = useState(!initialStars); const [error, setError] = useState(null); useEffect(() => { const fetchStars = async () => { // 如果有初始值,不需要立即获取 if (initialStars !== undefined) return; try { const response = await fetch( `/api/github?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`, ); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error || `HTTP error! status: ${response.status}`, ); } const data = await response.json(); setStars(data.stars); setError(null); } catch (error) { console.error("Error fetching GitHub stars:", error); setError( error instanceof Error ? error.message : "Failed to fetch stars", ); } finally { setLoading(false); } }; if (owner && repo) { fetchStars(); } }, [owner, repo, initialStars]); return ( GitHub {loading ? ( ) : ( {nFormatter(stars)} stars )} ); }; export default GitHubStarsButton;