Open History to see the last commit
1import { createContext } from 'preact'
2import { useContext, useEffect } from 'preact/hooks'
3import type { QueryClient } from '@tanstack/query-core'
4import type { ComponentChildren, VNode } from 'preact'
5β
6/**
7 * The context that `useQueryClient` reads from. `QueryClientProvider` is the
8 * normal way to set it.
9 */
10export const QueryClientContext = createContext<QueryClient | undefined>(
11 undefined,
12)
13β
14/**
15 * The `useQueryClient` hook returns the current `QueryClient` instance.
16 *
17 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
18 * one from the nearest context will be used.
19 * @returns The current `QueryClient` instance.
20 * @throws {Error} If no `queryClient` argument is passed and no
21 * `QueryClientProvider` is found in the component tree.
22 */
23export const useQueryClient = (queryClient?: QueryClient) => {
24 const client = useContext(QueryClientContext)
25β
26 if (queryClient) {
27 return queryClient
28 }
29β
30 if (!client) {
31 throw new Error('No QueryClient set, use QueryClientProvider to set one')
32 }
33β
34 return client
35}
36β
37/** The props accepted by `QueryClientProvider`. */
38export type QueryClientProviderProps = {
39 /**
40 * **Required**
41 *
42 * The `QueryClient` instance to provide.
43 */
44 client: QueryClient
45 /** The components that get access to the provided `QueryClient`. */
46 children?: ComponentChildren
47}
48β
49/**
50 * Use the `QueryClientProvider` component to connect and provide a
51 * `QueryClient` to your application. Also calls
52 * `client.mount()`/`client.unmount()` as this component mounts/unmounts, which
53 * subscribes the client to focus/online events (resuming any paused mutations
54 * and refetching as needed when the app regains focus or comes back online).
55 *
56 * @example
57 * ;```tsx
58 * import { QueryClient, QueryClientProvider } from '@tanstack/preact-query'
59 *
60 * const queryClient = new QueryClient()
61 *
62 * function App() {
63 * return (
64 * <QueryClientProvider client={queryClient}>...</QueryClientProvider>
65 * )
66 * }
67 * ```
68 *
69 * @param props - The `client` to provide, and the `children` that get access to
70 * it.
71 * @returns The provided `children`, wrapped so they can read the `QueryClient`
72 * via `useQueryClient`.
73 */
74export const QueryClientProvider = ({
75 client,
76 children,
77}: QueryClientProviderProps): VNode => {
78 useEffect(() => {
79 client.mount()
80 return () => {
81 client.unmount()
82 }
83 }, [client])
84β
85 return (
86 <QueryClientContext.Provider value={client}>
87 {children}
88 </QueryClientContext.Provider>
89 )
90}