Open History to see the last commit
1import { createContext, useContext } from 'octane'
2import type { QueryClient } from '@tanstack/query-core'
3β
4// The QueryClient context β read by useQuery/useMutation/useQueryClient. Mirrors
5// react-query's QueryClientContext.
6export const QueryClientContext = createContext<QueryClient | undefined>(
7 undefined,
8)
9β
10// Resolve the client: an explicitly-passed one wins, else the context value.
11// `useContext` is keyed by context identity (not a per-call-site slot), so it's
12// safe to call from this binding code without a compiler-injected slot.
13export function resolveClient(
14 queryClient: QueryClient | undefined,
15): QueryClient {
16 const ctxClient = useContext(QueryClientContext)
17 const client = queryClient ?? ctxClient
18 if (!client) {
19 throw new Error('No QueryClient set, use QueryClientProvider to set one')
20 }
21 return client
22}
23β
24// Signature matches @tanstack/react-query's QueryClientProvider.tsx.
25export function useQueryClient(queryClient?: QueryClient): QueryClient
26β
27export function useQueryClient(...args: Array<unknown>): QueryClient {
28 // Args are `[queryClient?, slot?]`; the slot (symbol) is appended by the
29 // compiler. An explicit client is the first non-symbol arg.
30 const queryClient =
31 args.length && typeof args[0] !== 'symbol'
32 ? (args[0] as QueryClient)
33 : undefined
34 return resolveClient(queryClient)
35}