my fork of the bluesky client
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)
13const apiContext = React.createContext<ApiContext>({
14 setInviteCopied(_: string) {},
15})
16
17export function Provider({children}: React.PropsWithChildren<{}>) {
18 const [state, setState] = React.useState(persisted.get('invites'))
19
20 const api = React.useMemo(
21 () => ({
22 setInviteCopied(code: string) {
23 setState(state => {
24 state = {
25 ...state,
26 copiedInvites: state.copiedInvites.includes(code)
27 ? state.copiedInvites
28 : state.copiedInvites.concat([code]),
29 }
30 persisted.write('invites', state)
31 return state
32 })
33 },
34 }),
35 [setState],
36 )
37
38 React.useEffect(() => {
39 return persisted.onUpdate('invites', nextInvites => {
40 setState(nextInvites)
41 })
42 }, [setState])
43
44 return (
45 <stateContext.Provider value={state}>
46 <apiContext.Provider value={api}>{children}</apiContext.Provider>
47 </stateContext.Provider>
48 )
49}
50
51export function useInvitesState() {
52 return React.useContext(stateContext)
53}
54
55export function useInvitesAPI() {
56 return React.useContext(apiContext)
57}