Spaces:
Running
Running
File size: 1,832 Bytes
72f0edb |
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import {
useState,
useEffect,
createContext,
useContext,
ReactNode,
} from "react";
import { ContentItem } from "../lib/types";
interface MyListContextType {
myList: ContentItem[];
addToMyList: (item: ContentItem) => void;
removeFromMyList: (id: string) => void;
isInMyList: (id: string) => boolean;
}
const MyListContext = createContext<MyListContextType | undefined>(undefined);
export const MyListProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const [myList, setMyList] = useState<ContentItem[]>([]);
// Load saved items from local storage
useEffect(() => {
const savedList = localStorage.getItem("myList");
if (savedList) {
try {
setMyList(JSON.parse(savedList));
} catch (error) {
console.error("Failed to parse saved list:", error);
}
}
}, []);
// Save items to local storage when list changes
useEffect(() => {
localStorage.setItem("myList", JSON.stringify(myList));
}, [myList]);
const addToMyList = (item: ContentItem) => {
setMyList((prev) => {
// Only add if not already in list
if (!prev.some((listItem) => listItem.id === item.id)) {
return [...prev, item];
}
return prev;
});
};
const removeFromMyList = (id: string) => {
setMyList((prev) => prev.filter((item) => item.id !== id));
};
const isInMyList = (id: string) => {
return myList.some((item) => item.id === id);
};
return (
<MyListContext.Provider
value={{ myList, addToMyList, removeFromMyList, isInMyList }}
>
{children}
</MyListContext.Provider>
);
};
export const useMyList = () => {
const context = useContext(MyListContext);
if (context === undefined) {
throw new Error("useMyList must be used within a MyListProvider");
}
return context;
};
|