Repository navigation
Expand file tree
/
Copy pathQueryClientProvider.tsx
More file actions
68 lines (55 loc) · 1.73 KB
/
Copy pathQueryClientProvider.tsx
File metadata and controls
68 lines (55 loc) · 1.73 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
import React from 'react'
import { QueryClient } from '../core'
declare global {
interface Window {
ReactQueryClientContext?: React.Context<QueryClient | undefined>
}
}
const defaultContext = React.createContext<QueryClient | undefined>(undefined)
const QueryClientSharingContext = React.createContext<boolean>(false)
// if contextSharing is on, we share the first and at least one
// instance of the context across the window
// to ensure that if React Query is used across
// different bundles or microfrontends they will
// all use the same **instance** of context, regardless
// of module scoping.
function getQueryClientContext(contextSharing: boolean) {
if (contextSharing && typeof window !== 'undefined') {
if (!window.ReactQueryClientContext) {
window.ReactQueryClientContext = defaultContext
}
return window.ReactQueryClientContext
}
return defaultContext
}
export const useQueryClient = () => {
const queryClient = React.useContext(
getQueryClientContext(React.useContext(QueryClientSharingContext))
)
if (!queryClient) {
throw new Error('No QueryClient set, use QueryClientProvider to set one')
}
return queryClient
}
export interface QueryClientProviderProps {
client: QueryClient
contextSharing?: boolean
}
export const QueryClientProvider: React.FC<QueryClientProviderProps> = ({
client,
contextSharing = false,
children,
}) => {
React.useEffect(() => {
client.mount()
return () => {
client.unmount()
}
}, [client])
const Context = getQueryClientContext(contextSharing)
return (
<QueryClientSharingContext.Provider value={contextSharing}>
<Context.Provider value={client}>{children}</Context.Provider>
</QueryClientSharingContext.Provider>
)
}