-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFavoritesContext.tsx
46 lines (38 loc) · 1.01 KB
/
FavoritesContext.tsx
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
import {
createContext,
useState,
Dispatch,
SetStateAction,
ReactNode,
useEffect,
} from 'react';
import { Starship } from '@/types';
export interface IFavoritesContext {
favorites: Starship[];
setFavorites: Dispatch<SetStateAction<Starship[]>>;
}
const defaultCtx = {
favorites: [],
setFavorites: () => {},
} as IFavoritesContext;
export const FavoritesContext = createContext<IFavoritesContext>(defaultCtx);
type FavoritesProviderProps = {
children: ReactNode;
};
const getInitialState = () => {
const favorites = localStorage.getItem('favorites');
return favorites ? JSON.parse(favorites) : [];
};
export default function FavoritesProvider({
children,
}: FavoritesProviderProps) {
const [favorites, setFavorites] = useState<Starship[]>(getInitialState);
useEffect(() => {
localStorage.setItem('favorites', JSON.stringify(favorites));
}, [favorites]);
return (
<FavoritesContext.Provider value={{ favorites, setFavorites }}>
{children}
</FavoritesContext.Provider>
);
}