fix(filters): merge defaults and stored value
All checks were successful
Release to Staging / build_and_release (push) Successful in 50s

This commit is contained in:
enes 2024-11-18 11:52:42 +01:00
parent f3ab7f6d6a
commit 870262fcdc

View File

@ -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(() => {