From b60659eebff856667a85c02e745dfba60ea0a5cf Mon Sep 17 00:00:00 2001 From: enes Date: Thu, 9 Jan 2025 13:19:17 +0100 Subject: [PATCH] feat(cache): add simple localcache hook --- src/hooks/index.ts | 1 + src/hooks/useLocalCache.tsx | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/hooks/useLocalCache.tsx 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] +}