-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotesContext.tsx
46 lines (37 loc) · 1.08 KB
/
NotesContext.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 { ReactNode, createContext, useEffect, useState } from 'react';
import { Starship } from '@/types';
type NotesContextType = {
notes: { [key: string]: string };
setNote: (ship: Starship, note: string) => void;
};
const defaultCtx = {
notes: {},
setNote: () => {},
} as NotesContextType;
export const NotesContext = createContext<NotesContextType>(defaultCtx);
type NotesProviderProps = {
children: ReactNode;
};
const getInitialState = () => {
const notes = localStorage.getItem('notes');
return notes ? JSON.parse(notes) : {};
};
export default function NotesProvider({ children }: NotesProviderProps) {
const [notes, setNotes] = useState<{ [key: string]: string }>(
getInitialState
);
useEffect(() => {
localStorage.setItem('notes', JSON.stringify(notes));
}, [notes]);
const setNote = (ship: Starship, note: string) => {
setNotes((prevNotes) => ({
...prevNotes,
[`${ship.name}-${ship.manufacturer}`]: note,
}));
};
return (
<NotesContext.Provider value={{ notes, setNote }}>
{children}
</NotesContext.Provider>
);
}