diff --git a/src/hooks/useLocalStorage.tsx b/src/hooks/useLocalStorage.tsx index 8dc9893..4d1eac2 100644 --- a/src/hooks/useLocalStorage.tsx +++ b/src/hooks/useLocalStorage.tsx @@ -10,11 +10,29 @@ const useLocalStorageSubscribe = (callback: () => void) => { return () => window.removeEventListener('storage', callback) } +function mergeWithInitialValue(storedValue: T, initialValue: T): T { + if (typeof storedValue === 'object' && storedValue !== null) { + return { ...initialValue, ...storedValue } + } + return storedValue +} + export function useLocalStorage( key: string, initialValue: T ): [T, React.Dispatch>] { - const getSnapshot = () => getLocalStorageItem(key, initialValue) + const getSnapshot = () => { + // Get the stored value + const storedValue = getLocalStorageItem(key, initialValue) + + // Parse the value + const parsedStoredValue = JSON.parse(storedValue) + + // Merge the default and the stored in case some of the required fields are missing + return JSON.stringify( + mergeWithInitialValue(parsedStoredValue, initialValue) + ) + } const data = React.useSyncExternalStore(useLocalStorageSubscribe, getSnapshot) @@ -35,7 +53,7 @@ export function useLocalStorage( console.warn(e) } }, - [key, data] + [data, key] ) React.useEffect(() => {