about summary refs log tree commit diff
path: root/src/state/preferences/used-starter-packs.tsx
blob: 302b0e1f4a22bd45217dba38247becd83c77fc6b (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
import React from 'react'

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

type StateContext = boolean | undefined
type SetContext = (v: boolean) => void

const stateContext = React.createContext<StateContext>(false)
stateContext.displayName = 'UsedStarterPacksStateContext'
const setContext = React.createContext<SetContext>((_: boolean) => {})
setContext.displayName = 'UsedStarterPacksSetContext'

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

  const setStateWrapped = (v: boolean) => {
    setState(v)
    persisted.write('hasCheckedForStarterPack', v)
  }

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

  return (
    <stateContext.Provider value={state}>
      <setContext.Provider value={setStateWrapped}>
        {children}
      </setContext.Provider>
    </stateContext.Provider>
  )
}

export const useHasCheckedForStarterPack = () => React.useContext(stateContext)
export const useSetHasCheckedForStarterPack = () => React.useContext(setContext)