Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "http-react",
"version": "3.8.4",
"version": "3.8.5",
"description": "React hooks for data fetching",
"main": "dist/index.js",
"scripts": {
Expand Down
84 changes: 84 additions & 0 deletions src/components/LocalStorageCacheProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
'use client'

import React from 'react'
import { defaultCache, FetchConfig, useIsomorphicLayoutEffect } from '../'

let isCacheHydrated = false

const loadFromLocalStorage = () => {
if (typeof localStorage !== 'undefined') {
for (let key in localStorage) {
try {
const currentValue = localStorage.getItem(key)
if (typeof currentValue !== 'undefined') {
console.log({ key, currentValue })

defaultCache.set(key, JSON.parse(currentValue!))
}
} catch (error) {
// Remove cache key if parsing fails
localStorage.removeItem(key)
}
}

isCacheHydrated = true
console.log('Cache hydration complete.')
}
}

function useCacheHydration({ instant }: { instant?: boolean }) {
if (instant && !isCacheHydrated) {
loadFromLocalStorage()
}

useIsomorphicLayoutEffect(() => {
if (!isCacheHydrated && !instant) {
const handle = window.requestIdleCallback(loadFromLocalStorage)

return () => window.cancelIdleCallback(handle)
}

return () => {}
}, [instant])
}

/**
* Provider component to configure the fetch library with a persistent cache.
* Uses in-memory cache (defaultCache) for fast access and localStorage (storage)
* for persistence, with asynchronous writes and deferred hydration.
*/
export function LocalStorageCacheProvider({
children,
instant
}: React.PropsWithChildren<{ instant?: boolean }>) {
useCacheHydration({ instant })

return (
// @ts-expect-error
<FetchConfig
cacheProvider={{
get(k) {
return defaultCache.get(k)
},

set(k, v) {
defaultCache.set(k, v)

queueMicrotask(() => {
localStorage.setItem(k, JSON.stringify(v))
})
},

remove(k) {
defaultCache.remove?.(k)

queueMicrotask(() => {
localStorage.removeItem(k)
})
}
}}
>
{children}
</FetchConfig>
)
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export {

export { FetchConfig, SSRSuspense } from './components/server'
export { SSRSuspense as Suspense } from './components/server'
export { LocalStorageCacheProvider } from './components/LocalStorageCacheProvider'

export {
queryProvider,
Expand Down