MCPcopy Create free account
hub / github.com/dailydotdev/apps / usePersistentState

Function usePersistentState

packages/shared/src/hooks/usePersistentState.ts:4–46  ·  view source on GitHub ↗
(
  key: string,
  initialValue: T,
  valueWhenCacheEmpty?: T,
  persistIfEmpty?: boolean,
)

Source from the content-addressed store, hash-verified

2import { get as getCache, set as setCache } from 'idb-keyval';
3
4export 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}

Callers 2

AuthOptionsInnerFunction · 0.90
BriefContext.tsxFile · 0.90

Calls 1

setValueAndPersistFunction · 0.85

Tested by

no test coverage detected