MCPcopy Create free account
hub / github.com/dfinity/orbit / useStorage

Function useStorage

apps/wallet/src/utils/storage.utils.ts:7–53  ·  view source on GitHub ↗
({
  key,
  storage,
  initial,
  serialize,
  deserialize,
  deepWatch = true,
}: {
  key: string;
  storage: Storage;
  initial: () => T;
  serialize: (value: T) => string;
  deserialize: (value: string) => T;
  deepWatch?: boolean;
})

Source from the content-addressed store, hash-verified

5export const objectDeserialize = <T>(value: string): T => JSON.parse(value);
6
7export function useStorage<T>({
8 key,
9 storage,
10 initial,
11 serialize,
12 deserialize,
13 deepWatch = true,
14}: {
15 key: string;
16 storage: Storage;
17 initial: () => T;
18 serialize: (value: T) => string;
19 deserialize: (value: string) => T;
20 deepWatch?: boolean;
21}): Ref<T> {
22 const storedValue: string | null = storage.getItem(key);
23 const valueIsStored = storedValue !== null;
24
25 let initialValue: T;
26
27 if (valueIsStored) {
28 try {
29 initialValue = deserialize(storedValue);
30 } catch (error) {
31 logger.warn(`Failed to deserialize value for key ${key}: ${storedValue}`, error);
32 initialValue = initial();
33 }
34 } else {
35 initialValue = initial();
36 }
37
38 const data = ref(initialValue) as Ref<T>;
39
40 if (!valueIsStored) {
41 storage.setItem(key, serialize(initialValue));
42 }
43
44 watch(
45 data,
46 newValue => {
47 storage.setItem(key, serialize(newValue));
48 },
49 { deep: deepWatch },
50 );
51
52 return data;
53}

Callers 2

session.store.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected