diff --git a/src/hooks/index.ts b/src/hooks/index.ts index c01237e..e0f6038 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -9,3 +9,4 @@ export * from './useNDKContext' export * from './useScrollDisable' export * from './useLocalStorage' export * from './useSessionStorage' +export * from './useLocalCache' diff --git a/src/hooks/useLocalCache.tsx b/src/hooks/useLocalCache.tsx new file mode 100644 index 0000000..7dc1d9a --- /dev/null +++ b/src/hooks/useLocalCache.tsx @@ -0,0 +1,37 @@ +import { useCallback, useEffect, useState } from 'react' +import { setLocalStorageItem, removeLocalStorageItem } from 'utils' + +export function useLocalCache( + key: string +): [ + T | undefined, + React.Dispatch>, + () => void +] { + const [cache, setCache] = useState(() => { + const storedValue = window.localStorage.getItem(key) + if (storedValue === null) return undefined + + // Parse the value + const parsedStoredValue = JSON.parse(storedValue) + return parsedStoredValue + }) + + useEffect(() => { + try { + if (cache) { + setLocalStorageItem(key, JSON.stringify(cache)) + } else { + removeLocalStorageItem(key) + } + } catch (e) { + console.warn(e) + } + }, [cache, key]) + + const clearCache = useCallback(() => { + setCache(undefined) + }, []) + + return [cache, setCache, clearCache] +}