refactor(favorites): replace localStorage with centralized favorite store
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import { Heart } from "lucide-react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useRequireAuth } from "@/lib/use-require-auth"
|
||||
import { useAuthStore } from "@/store/auth"
|
||||
import { useFavoriteStore } from "@/store/favorites"
|
||||
|
||||
interface FavoriteButtonProps {
|
||||
initialFavorited: boolean
|
||||
@@ -13,26 +13,13 @@ interface FavoriteButtonProps {
|
||||
}
|
||||
|
||||
export function FavoriteButton({ initialFavorited, targetType, targetId }: FavoriteButtonProps) {
|
||||
const [favorited, setFavorited] = useState(initialFavorited)
|
||||
const { requireAuth } = useRequireAuth()
|
||||
const userId = useAuthStore((s) => s.user?.id)
|
||||
const storageKey = useMemo(
|
||||
() => `favorite:${userId ?? "guest"}:${targetType}:${targetId}`,
|
||||
[userId, targetType, targetId],
|
||||
const favoritedInStore = useFavoriteStore((state) =>
|
||||
userId ? state.isFavorited(userId, targetType, targetId) : false,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem(storageKey)
|
||||
if (stored === "1") {
|
||||
setFavorited(true)
|
||||
return
|
||||
}
|
||||
if (stored === "0") {
|
||||
setFavorited(false)
|
||||
return
|
||||
}
|
||||
setFavorited(initialFavorited)
|
||||
}, [storageKey, initialFavorited])
|
||||
const toggleFavorite = useFavoriteStore((state) => state.toggleFavorite)
|
||||
const favorited = userId ? favoritedInStore : initialFavorited
|
||||
|
||||
return (
|
||||
<Button
|
||||
@@ -40,13 +27,10 @@ export function FavoriteButton({ initialFavorited, targetType, targetId }: Favor
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() =>
|
||||
requireAuth(() =>
|
||||
setFavorited((prev) => {
|
||||
const next = !prev
|
||||
window.localStorage.setItem(storageKey, next ? "1" : "0")
|
||||
return next
|
||||
}),
|
||||
)
|
||||
requireAuth(() => {
|
||||
if (!userId) return
|
||||
toggleFavorite(userId, targetType, targetId)
|
||||
})
|
||||
}
|
||||
>
|
||||
<Heart className={`h-4 w-4 ${favorited ? "fill-current" : ""}`} />
|
||||
|
||||
Reference in New Issue
Block a user