({
key,
storage,
initial,
serialize,
deserialize,
deepWatch = true,
}: {
key: string;
storage: Storage;
initial: () => T;
serialize: (value: T) => string;
deserialize: (value: string) => T;
deepWatch?: boolean;
})
| 5 | export const objectDeserialize = <T>(value: string): T => JSON.parse(value); |
| 6 | |
| 7 | export 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 | } |
no outgoing calls
no test coverage detected