-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefs.js
52 lines (41 loc) · 1.28 KB
/
prefs.js
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
import { useContext, useEffect, useMemo, useState } from 'preact/hooks'
import { createContext } from 'preact'
const Preferences = createContext({})
const KEY = 'preferences'
const PreferencesWrapper = props => {
// On load, read the preferences from localstorage and add any missing defaults
const [preferences, setPreferences] = useState({
...props.default,
...(window.localStorage.getItem(KEY)
? JSON.parse(window.localStorage.getItem(KEY))
: {})
})
// When preferences changes, update localStorage
useEffect(() => {
window.localStorage.setItem(KEY, JSON.stringify(preferences))
}, [preferences])
return (
<Preferences.Provider
value={{
preferences,
setPreferences
}}
>
{props.children}
</Preferences.Provider>
)
}
const usePreference = key => {
const { preferences, setPreferences } = useContext(Preferences)
// Get preference value if exists
const value = Object.prototype.hasOwnProperty.call(preferences, key)
? preferences[key]
: null
// Memoize a setter for the preference
const setter = useMemo(
() => value => setPreferences({ ...preferences, [key]: value }),
[preferences, setPreferences]
)
return [value, setter]
}
export { PreferencesWrapper, Preferences, usePreference }