-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLocalStorageCacheProvider.tsx
More file actions
81 lines (67 loc) · 1.85 KB
/
LocalStorageCacheProvider.tsx
File metadata and controls
81 lines (67 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'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') {
defaultCache.set(key, JSON.parse(currentValue!))
}
} catch (error) {
// Remove cache key if parsing fails
localStorage.removeItem(key)
}
}
isCacheHydrated = true
}
}
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>
)
}