'init'
Some checks failed
Upstream Sync / Sync latest commits from upstream repo (push) Has been cancelled
Some checks failed
Upstream Sync / Sync latest commits from upstream repo (push) Has been cancelled
This commit is contained in:
49
mobile/context/BindContext.tsx
Normal file
49
mobile/context/BindContext.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import type { BindPayload } from '@/lib/types'
|
||||
import { clearBindPayload, loadBindPayload, saveBindPayload } from '@/lib/storage'
|
||||
|
||||
type Ctx = {
|
||||
bind: BindPayload | null
|
||||
ready: boolean
|
||||
setBind: (p: BindPayload | null) => Promise<void>
|
||||
clear: () => Promise<void>
|
||||
}
|
||||
|
||||
const BindContext = createContext<Ctx | null>(null)
|
||||
|
||||
export function BindProvider({ children }: { children: React.ReactNode }) {
|
||||
const [bind, setBindState] = useState<BindPayload | null>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
const p = await loadBindPayload()
|
||||
setBindState(p)
|
||||
setReady(true)
|
||||
})()
|
||||
}, [])
|
||||
|
||||
const setBind = useCallback(async (p: BindPayload | null) => {
|
||||
setBindState(p)
|
||||
if (p) await saveBindPayload(p)
|
||||
else await clearBindPayload()
|
||||
}, [])
|
||||
|
||||
const clear = useCallback(async () => {
|
||||
setBindState(null)
|
||||
await clearBindPayload()
|
||||
}, [])
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ bind, ready, setBind, clear }),
|
||||
[bind, ready, setBind, clear],
|
||||
)
|
||||
|
||||
return <BindContext.Provider value={value}>{children}</BindContext.Provider>
|
||||
}
|
||||
|
||||
export function useBind(): Ctx {
|
||||
const c = useContext(BindContext)
|
||||
if (!c) throw new Error('useBind outside BindProvider')
|
||||
return c
|
||||
}
|
||||
Reference in New Issue
Block a user