blob: 962ac2d584764a2f17e5018807863060e8fab8f5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import { useState } from "react";
/**
* A simple hook for managing favorite items in localStorage.
* @param key LocalStorage key to use
* @returns [favorites, toggleFavorite, isFavorite]
*/
export function useFavorites(key: string) {
const [favorites, setFavorites] = useState<string[]>(() => {
if (typeof window === "undefined") return [];
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : [];
});
const toggleFavorite = (id: string) => {
setFavorites((prev) => {
const next = prev.includes(id)
? prev.filter((item) => item !== id)
: [...prev, id];
localStorage.setItem(key, JSON.stringify(next));
return next;
});
};
const isFavorite = (id: string) => favorites.includes(id);
return { favorites, toggleFavorite, isFavorite };
}
|