refactor(favorites): replace localStorage with centralized favorite store
This commit is contained in:
@@ -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
|
||||
},
|
||||
}))
|
||||
Reference in New Issue
Block a user