Open History to see the last commit
1import type { QueryClient } from '@tanstack/query-core'
2import { createContext } from 'preact'
3import type { ComponentChildren, VNode } from 'preact'
4import { useContext, useEffect } from 'preact/hooks'
5β
6export const QueryClientContext = createContext<QueryClient | undefined>(
7 undefined,
8)
9β
10export const useQueryClient = (queryClient?: QueryClient) => {
11 const client = useContext(QueryClientContext)
12β
13 if (queryClient) {
14 return queryClient
15 }
16β
17 if (!client) {
18 throw new Error('No QueryClient set, use QueryClientProvider to set one')
19 }
20β
21 return client
22}
23β
24export type QueryClientProviderProps = {
25 client: QueryClient
26 children?: ComponentChildren
27}
28β
29export const QueryClientProvider = ({
30 client,
31 children,
32}: QueryClientProviderProps): VNode => {
33 useEffect(() => {
34 client.mount()
35 return () => {
36 client.unmount()
37 }
38 }, [client])
39β
40 return (
41 <QueryClientContext.Provider value={client}>
42 {children}
43 </QueryClientContext.Provider>
44 )
45}