From 237cf90f5e209e2586a3662587e14da8076403c7 Mon Sep 17 00:00:00 2001 From: zetaloop Date: Sun, 22 Feb 2026 08:29:37 +0800 Subject: [PATCH] refactor(favorites): replace localStorage with centralized favorite store --- components/favorite-button.tsx | 34 ++++++---------------- lib/api/favorites.ts | 20 +++++++------ store/favorites.ts | 52 ++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 34 deletions(-) create mode 100644 store/favorites.ts diff --git a/components/favorite-button.tsx b/components/favorite-button.tsx index 09f2150..e08ec9b 100644 --- a/components/favorite-button.tsx +++ b/components/favorite-button.tsx @@ -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 (