feat(posts): wire community pages to backend posts API

This commit is contained in:
zetaloop
2026-02-28 17:25:57 +08:00
parent bffd8b4968
commit e94a7e68ff
5 changed files with 204 additions and 127 deletions
+36 -11
View File
@@ -1,34 +1,59 @@
"use client"
import { togglePostLike } from "@/lib/api/posts"
import { toApiError } from "@/lib/errors"
import { notifyInfo } from "@/lib/toast"
import { useRequireAuth } from "@/lib/use-require-auth"
import { usePostStore } from "@/store/posts"
import { Heart } from "lucide-react"
import { useState } from "react"
interface PostLikeButtonProps {
postId: string
initialLiked: boolean
initialLikeCount: number
}
export function PostLikeButton({ postId }: PostLikeButtonProps) {
export function PostLikeButton({ postId, initialLiked, initialLikeCount }: PostLikeButtonProps) {
const { requireAuth } = useRequireAuth()
const post = usePostStore((state) => state.posts.find((item) => item.id === postId))
if (!post) {
return null
}
const [liked, setLiked] = useState(initialLiked)
const [likeCount, setLikeCount] = useState(initialLikeCount)
const [pending, setPending] = useState(false)
return (
<button
type="button"
className="flex items-center gap-1 hover:text-foreground transition-colors"
disabled={pending}
className="flex items-center gap-1 hover:text-foreground transition-colors disabled:opacity-60 disabled:pointer-events-none"
onClick={() =>
requireAuth(() => {
togglePostLike(postId)
if (pending) return
const prevLiked = liked
const prevCount = likeCount
const nextLiked = !prevLiked
setLiked(nextLiked)
setLikeCount(Math.max(0, prevCount + (nextLiked ? 1 : -1)))
setPending(true)
togglePostLike(postId, prevLiked)
.catch((err: unknown) => {
setLiked(prevLiked)
setLikeCount(prevCount)
if (err instanceof Error && err.message === "UNAUTHORIZED") {
notifyInfo("请先登录")
return
}
notifyInfo(toApiError(err).msg)
})
.finally(() => {
setPending(false)
})
})
}
>
<Heart className={`h-4 w-4 ${post.liked ? "fill-red-500 text-red-500" : ""}`} />
{post.likeCount}
<Heart className={`h-4 w-4 ${liked ? "fill-red-500 text-red-500" : ""}`} />
{likeCount}
</button>
)
}