WoT implemented, plus other fixes #160
@ -10,11 +10,29 @@ const useLocalStorageSubscribe = (callback: () => void) => {
|
|||||||
return () => window.removeEventListener('storage', callback)
|
return () => window.removeEventListener('storage', callback)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mergeWithInitialValue<T>(storedValue: T, initialValue: T): T {
|
||||||
|
if (typeof storedValue === 'object' && storedValue !== null) {
|
||||||
|
return { ...initialValue, ...storedValue }
|
||||||
|
}
|
||||||
|
return storedValue
|
||||||
|
}
|
||||||
|
|
||||||
export function useLocalStorage<T>(
|
export function useLocalStorage<T>(
|
||||||
key: string,
|
key: string,
|
||||||
initialValue: T
|
initialValue: T
|
||||||
): [T, React.Dispatch<React.SetStateAction<T>>] {
|
): [T, React.Dispatch<React.SetStateAction<T>>] {
|
||||||
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)
|
const data = React.useSyncExternalStore(useLocalStorageSubscribe, getSnapshot)
|
||||||
|
|
||||||
@ -35,7 +53,7 @@ export function useLocalStorage<T>(
|
|||||||
console.warn(e)
|
console.warn(e)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[key, data]
|
[data, key]
|
||||||
)
|
)
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
|
Loading…
Reference in New Issue
Block a user