-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupsContext.tsx
48 lines (39 loc) · 1.33 KB
/
GroupsContext.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
47
48
// GroupsContext.tsx
import React, { createContext, useState } from 'react';
import { Group } from './types';
interface GroupsContextProps {
groups: Group[];
addGroup: (group: Group) => void;
updateGroup: (group: Group) => void;
deleteGroup: (groupId: string) => void;
}
const initialState: Group[] = JSON.parse(localStorage.getItem('groups') || '[]');
export const GroupsContext = createContext<GroupsContextProps>({
groups: initialState,
addGroup: () => {},
updateGroup: () => {},
deleteGroup: () => {}
});
export const GroupsProvider: React.FC = ({ children }) => {
const [groups, setGroups] = useState<Group[]>(initialState);
const saveGroups = (groups: Group[]) => {
localStorage.setItem('groups', JSON.stringify(groups));
setGroups(groups);
};
const addGroup = (newGroup: Group) => {
saveGroups([...groups, newGroup]);
};
const updateGroup = (updatedGroup: Group) => {
const updatedGroups = groups.map(group => group.id === updatedGroup.id ? updatedGroup : group);
saveGroups(updatedGroups);
};
const deleteGroup = (groupId: string) => {
const updatedGroups = groups.filter(group => group.id !== groupId);
saveGroups(updatedGroups);
};
return (
<GroupsContext.Provider value={{ groups, addGroup, updateGroup, deleteGroup }}>
{children}
</GroupsContext.Provider>
);
};