Open History to see the last commit
1import React from 'react'
2β
3import { QueryClient } from '../core'
4β
5const QueryClientContext = (() => {
6 const context = React.createContext<QueryClient | undefined>(undefined)
7 if (typeof window !== 'undefined') {
8 // @ts-ignore
9 window.ReactQueryClientContext = context
10 }
11 return context
12})()
13β
14function getQueryClientContext() {
15 return typeof window !== 'undefined'
16 ? // @ts-ignore
17 (window.ReactQueryClientContext as React.Context<
18 QueryClient | undefined
19 >) ?? QueryClientContext
20 : QueryClientContext
21}
22β
23export const useQueryClient = () => {
24 const queryClient = React.useContext(getQueryClientContext())
25β
26 if (!queryClient) {
27 throw new Error('No QueryClient set, use QueryClientProvider to set one')
28 }
29β
30 return queryClient
31}
32β
33export interface QueryClientProviderProps {
34 client: QueryClient
35}
36β
37export const QueryClientProvider: React.FC<QueryClientProviderProps> = ({
38 client,
39 children,
40}) => {
41 React.useEffect(() => {
42 client.mount()
43 return () => {
44 client.unmount()
45 }
46 }, [client])
47β
48 const Context = getQueryClientContext()
49β
50 return <Context.Provider value={client}>{children}</Context.Provider>
51}