celo-poll/components/social/FollowButton.tsx
2025-12-08 16:31:30 +03:00

72 lines
2.2 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import sdk from '@farcaster/frame-sdk'
import { UserPlus, UserMinus } from 'lucide-react'
interface FollowButtonProps {
targetFid: string
showCount?: boolean
}
export default function FollowButton({ targetFid, showCount = false }: FollowButtonProps) {
const [isFollowing, setIsFollowing] = useState(false)
const [followerCount, setFollowerCount] = useState(0)
const [loading, setLoading] = useState(false)
const [currentFid, setCurrentFid] = useState<string>('')
useEffect(() => {
sdk.context.then(ctx => {
if (ctx?.user?.fid) {
const fid = ctx.user.fid.toString()
setCurrentFid(fid)
Promise.all([
fetch(`/api/user/${fid}/following`).then(r => r.json()),
fetch(`/api/user/${targetFid}/followers`).then(r => r.json())
]).then(([followingData, followersData]) => {
setIsFollowing(followingData.following?.includes(targetFid) || false)
setFollowerCount(followersData.followers?.length || 0)
})
}
})
}, [targetFid])
const handleToggle = async () => {
if (!currentFid || currentFid === targetFid) return
setLoading(true)
const method = isFollowing ? 'DELETE' : 'POST'
await fetch(`/api/user/${targetFid}/follow`, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ followerFid: currentFid })
})
setIsFollowing(!isFollowing)
setFollowerCount(prev => isFollowing ? prev - 1 : prev + 1)
setLoading(false)
}
if (!currentFid || currentFid === targetFid) return null
return (
<button
onClick={handleToggle}
disabled={loading}
className={`flex items-center gap-2 px-4 py-2 rounded-lg font-semibold transition ${
isFollowing
? 'bg-white/10 text-white hover:bg-white/20'
: 'bg-celo-green text-black hover:bg-celo-green/90'
} disabled:opacity-50`}
>
{isFollowing ? <UserMinus size={16} /> : <UserPlus size={16} />}
{loading ? 'Loading...' : isFollowing ? 'Unfollow' : 'Follow'}
{showCount && followerCount > 0 && (
<span className="ml-1">({followerCount})</span>
)}
</button>
)
}