forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactQueryCacheProvider.tsx
47 lines (39 loc) · 1.13 KB
/
ReactQueryCacheProvider.tsx
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
import React from 'react'
import {
QueryCache,
queryCache as defaultQueryCache,
queryCaches,
} from '../core'
const queryCacheContext = React.createContext(defaultQueryCache)
export const useQueryCache = () => React.useContext(queryCacheContext)
export interface ReactQueryCacheProviderProps {
queryCache?: QueryCache
}
export const ReactQueryCacheProvider: React.FC<ReactQueryCacheProviderProps> = ({
queryCache,
children,
}) => {
const resolvedQueryCache = React.useMemo(
() => queryCache || new QueryCache(),
[queryCache]
)
React.useEffect(() => {
queryCaches.push(resolvedQueryCache)
return () => {
// remove the cache from the active list
const i = queryCaches.indexOf(resolvedQueryCache)
if (i > -1) {
queryCaches.splice(i, 1)
}
// if the resolvedQueryCache was created by us, we need to tear it down
if (queryCache == null) {
resolvedQueryCache.clear({ notify: false })
}
}
}, [resolvedQueryCache, queryCache])
return (
<queryCacheContext.Provider value={resolvedQueryCache}>
{children}
</queryCacheContext.Provider>
)
}