about summary refs log tree commit diff
path: root/src/state/invites.tsx
blob: 4f12cb12f4ad8a872629d09cf04a7417c70ff04b (plain) (blame)
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
49
50
51
52
53
54
55
56
57
58
59
import React from 'react'

import * as persisted from '#/state/persisted'

type StateContext = persisted.Schema['invites']
type ApiContext = {
  setInviteCopied: (code: string) => void
}

const stateContext = React.createContext<StateContext>(
  persisted.defaults.invites,
)
stateContext.displayName = 'InvitesStateContext'
const apiContext = React.createContext<ApiContext>({
  setInviteCopied(_: string) {},
})
apiContext.displayName = 'InvitesApiContext'

export function Provider({children}: React.PropsWithChildren<{}>) {
  const [state, setState] = React.useState(persisted.get('invites'))

  const api = React.useMemo(
    () => ({
      setInviteCopied(code: string) {
        setState(state => {
          state = {
            ...state,
            copiedInvites: state.copiedInvites.includes(code)
              ? state.copiedInvites
              : state.copiedInvites.concat([code]),
          }
          persisted.write('invites', state)
          return state
        })
      },
    }),
    [setState],
  )

  React.useEffect(() => {
    return persisted.onUpdate('invites', nextInvites => {
      setState(nextInvites)
    })
  }, [setState])

  return (
    <stateContext.Provider value={state}>
      <apiContext.Provider value={api}>{children}</apiContext.Provider>
    </stateContext.Provider>
  )
}

export function useInvitesState() {
  return React.useContext(stateContext)
}

export function useInvitesAPI() {
  return React.useContext(apiContext)
}