mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2
3import * as persisted from '#/state/persisted'
4
5type StateContext = persisted.Schema['invites']
6type ApiContext = {
7 setInviteCopied: (code: string) => void
8}
9
10const stateContext = React.createContext<StateContext>(
11 persisted.defaults.invites,
12)
13stateContext.displayName = 'InvitesStateContext'
14const apiContext = React.createContext<ApiContext>({
15 setInviteCopied(_: string) {},
16})
17apiContext.displayName = 'InvitesApiContext'
18
19export function Provider({children}: React.PropsWithChildren<{}>) {
20 const [state, setState] = React.useState(persisted.get('invites'))
21
22 const api = React.useMemo(
23 () => ({
24 setInviteCopied(code: string) {
25 setState(state => {
26 state = {
27 ...state,
28 copiedInvites: state.copiedInvites.includes(code)
29 ? state.copiedInvites
30 : state.copiedInvites.concat([code]),
31 }
32 persisted.write('invites', state)
33 return state
34 })
35 },
36 }),
37 [setState],
38 )
39
40 React.useEffect(() => {
41 return persisted.onUpdate('invites', nextInvites => {
42 setState(nextInvites)
43 })
44 }, [setState])
45
46 return (
47 <stateContext.Provider value={state}>
48 <apiContext.Provider value={api}>{children}</apiContext.Provider>
49 </stateContext.Provider>
50 )
51}
52
53export function useInvitesState() {
54 return React.useContext(stateContext)
55}
56
57export function useInvitesAPI() {
58 return React.useContext(apiContext)
59}