Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

QueryClientProvider.tsx

51 lines1.1 KB

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
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
32​
33export interface QueryClientProviderProps {
34 client: QueryClient
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>