mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2
3import {BackgroundNotificationHandlerPreferences} from './ExpoBackgroundNotificationHandler.types'
4import {BackgroundNotificationHandler} from './ExpoBackgroundNotificationHandlerModule'
5
6interface BackgroundNotificationPreferencesContext {
7 preferences: BackgroundNotificationHandlerPreferences
8 setPref: <Key extends keyof BackgroundNotificationHandlerPreferences>(
9 key: Key,
10 value: BackgroundNotificationHandlerPreferences[Key],
11 ) => void
12}
13
14const Context = React.createContext<BackgroundNotificationPreferencesContext>(
15 {} as BackgroundNotificationPreferencesContext,
16)
17export const useBackgroundNotificationPreferences = () =>
18 React.useContext(Context)
19
20export function BackgroundNotificationPreferencesProvider({
21 children,
22}: {
23 children: React.ReactNode
24}) {
25 const [preferences, setPreferences] =
26 React.useState<BackgroundNotificationHandlerPreferences>({
27 playSoundChat: true,
28 })
29
30 React.useEffect(() => {
31 ;(async () => {
32 const prefs = await BackgroundNotificationHandler.getAllPrefsAsync()
33 setPreferences(prefs)
34 })()
35 }, [])
36
37 const value = React.useMemo(
38 () => ({
39 preferences,
40 setPref: async <
41 Key extends keyof BackgroundNotificationHandlerPreferences,
42 >(
43 k: Key,
44 v: BackgroundNotificationHandlerPreferences[Key],
45 ) => {
46 switch (typeof v) {
47 case 'boolean': {
48 await BackgroundNotificationHandler.setBoolAsync(k, v)
49 break
50 }
51 case 'string': {
52 await BackgroundNotificationHandler.setStringAsync(k, v)
53 break
54 }
55 default: {
56 throw new Error(`Invalid type for value: ${typeof v}`)
57 }
58 }
59
60 setPreferences(prev => ({
61 ...prev,
62 [k]: v,
63 }))
64 },
65 }),
66 [preferences],
67 )
68
69 return <Context.Provider value={value}>{children}</Context.Provider>
70}