refactor(favorites): replace localStorage with centralized favorite store

This commit is contained in:
zetaloop
2026-02-22 08:29:37 +08:00
parent 8ce3b8a8b5
commit 237cf90f5e
3 changed files with 72 additions and 34 deletions
+52
View File
@@ -0,0 +1,52 @@
import { create } from "zustand"
import { generateId } from "@/lib/id"
import { mockFavorites } from "@/lib/mock"
import type { Favorite } from "@/lib/types"
interface FavoriteState {
favorites: Favorite[]
listFavoritesByUser: (userId: string) => Favorite[]
isFavorited: (userId: string, targetType: "player" | "shop", targetId: string) => boolean
toggleFavorite: (userId: string, targetType: "player" | "shop", targetId: string) => boolean
}
export const useFavoriteStore = create<FavoriteState>((set, get) => ({
favorites: mockFavorites,
listFavoritesByUser: (userId) => get().favorites.filter((favorite) => favorite.userId === userId),
isFavorited: (userId, targetType, targetId) =>
get().favorites.some(
(favorite) =>
favorite.userId === userId &&
favorite.targetType === targetType &&
favorite.targetId === targetId,
),
toggleFavorite: (userId, targetType, targetId) => {
const state = get()
const existing = state.favorites.find(
(favorite) =>
favorite.userId === userId &&
favorite.targetType === targetType &&
favorite.targetId === targetId,
)
if (existing) {
set((prev) => ({
favorites: prev.favorites.filter((favorite) => favorite.id !== existing.id),
}))
return false
}
const next: Favorite = {
id: generateId("fav"),
userId,
targetType,
targetId,
createdAt: new Date().toISOString(),
}
set((prev) => ({
favorites: [next, ...prev.favorites],
}))
return true
},
}))