MCPcopy Create free account
hub / github.com/Kilo-Org/cloud / useLocalStorage

Function useLocalStorage

apps/web/src/hooks/useLocalStorage/useLocalStorage.ts:46–188  ·  view source on GitHub ↗
(
  key: string,
  initialValue: T | (() => T),
  options: UseLocalStorageOptions<T> = {}
)

Source from the content-addressed store, hash-verified

44 * ```
45 */
46export function useLocalStorage<T>(
47 key: string,
48 initialValue: T | (() => T),
49 options: UseLocalStorageOptions<T> = {}
50): [T, Dispatch<SetStateAction<T>>, () => void] {
51 const { initializeWithValue = true } = options;
52
53 const serializer = useCallback<(value: T) => string>(
54 value => {
55 if (options.serializer) {
56 return options.serializer(value);
57 }
58
59 return JSON.stringify(value);
60 },
61 [options]
62 );
63
64 const deserializer = useCallback<(value: string) => T>(
65 value => {
66 if (options.deserializer) {
67 return options.deserializer(value);
68 }
69 // Support 'undefined' as a value
70 if (value === 'undefined') {
71 return undefined as unknown as T;
72 }
73
74 const defaultValue = initialValue instanceof Function ? initialValue() : initialValue;
75
76 let parsed: unknown;
77 try {
78 parsed = JSON.parse(value);
79 } catch (error) {
80 console.error('Error parsing JSON:', error);
81 return defaultValue; // Return initialValue if parsing fails
82 }
83
84 return parsed as T;
85 },
86 [options, initialValue]
87 );
88
89 // Get from local storage then
90 // parse stored json or return initialValue
91 const readValue = useCallback((): T => {
92 const initialValueToUse = initialValue instanceof Function ? initialValue() : initialValue;
93
94 // Prevent build error "window is undefined" but keep working
95 if (IS_SERVER) {
96 return initialValueToUse;
97 }
98
99 try {
100 const raw = window.localStorage.getItem(key);
101 return raw ? deserializer(raw) : initialValueToUse;
102 } catch (error) {
103 console.warn(`Error reading localStorage key “${key}”:`, error);

Callers 3

CloudSidebarLayoutFunction · 0.90
useCelebrationSoundFunction · 0.90
useNotificationSoundFunction · 0.90

Calls 7

useEventListenerFunction · 0.90
removeItemMethod · 0.80
errorMethod · 0.65
getItemMethod · 0.65
warnMethod · 0.65
setItemMethod · 0.65
valueFunction · 0.50

Tested by

no test coverage detected