( key: string, initialValue: T, valueWhenCacheEmpty?: T, persistIfEmpty?: boolean, )
| 2 | import { get as getCache, set as setCache } from 'idb-keyval'; |
| 3 | |
| 4 | export function usePersistentState<T>( |
| 5 | key: string, |
| 6 | initialValue: T, |
| 7 | valueWhenCacheEmpty?: T, |
| 8 | persistIfEmpty?: boolean, |
| 9 | ): [T, (value: T) => Promise<void>, boolean] { |
| 10 | const [value, setValue] = useState(initialValue); |
| 11 | const [loaded, setLoaded] = useState(false); |
| 12 | |
| 13 | const setValueAndPersist = (newValue: T): Promise<void> => { |
| 14 | if (newValue !== value) { |
| 15 | setValue(newValue); |
| 16 | return setCache(key, newValue); |
| 17 | } |
| 18 | return Promise.resolve(); |
| 19 | }; |
| 20 | |
| 21 | useEffect(() => { |
| 22 | getCache<T>(key) |
| 23 | .then(async (cachedValue) => { |
| 24 | if (cachedValue !== undefined) { |
| 25 | setValue(cachedValue); |
| 26 | } else if (valueWhenCacheEmpty !== undefined) { |
| 27 | if (persistIfEmpty) { |
| 28 | await setValueAndPersist(valueWhenCacheEmpty); |
| 29 | } else { |
| 30 | setValue(valueWhenCacheEmpty); |
| 31 | } |
| 32 | } |
| 33 | setLoaded(true); |
| 34 | }) |
| 35 | .catch(() => { |
| 36 | if (valueWhenCacheEmpty !== undefined) { |
| 37 | setValue(valueWhenCacheEmpty); |
| 38 | } |
| 39 | setLoaded(true); |
| 40 | }); |
| 41 | // @NOTE see https://dailydotdev.atlassian.net/l/cp/dK9h1zoM |
| 42 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 43 | }, []); |
| 44 | |
| 45 | return [value, setValueAndPersist, loaded]; |
| 46 | } |
no test coverage detected