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

useBaseQuery.ts

152 lines4.7 KB

1'use client'
2import * as React from 'react'
3​
4import { noop, notifyManager } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
7import {
8 ensurePreventErrorBoundaryRetry,
9 getHasError,
10 useClearResetErrorBoundary,
11} from './errorBoundaryUtils'
12import { useIsRestoring } from './IsRestoringProvider'
13import {
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 shouldSuspend,
17} from './suspense'
18import type {
19 QueryClient,
20 QueryKey,
21 QueryObserver,
22 QueryObserverResult,
23} from '@tanstack/query-core'
24import type { UseBaseQueryOptions } from './types'
25​
26/**
27 * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and
28 * `useSuspenseInfiniteQuery`.
29 * @param options - The options passed to the calling hook.
30 * @param Observer - The observer class from query-core (`QueryObserver` or
31 * `InfiniteQueryObserver`).
32 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
33 * context will be used.
34 * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is
35 * set.
36 * @throws {Error} If `options` is not an object (outside production), or the query error when it should be
37 * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead.
38 */
39export function useBaseQuery<
40 TQueryFnData,
41 TError,
42 TData,
43 TQueryData,
44 TQueryKey extends QueryKey,
45>(
46 options: UseBaseQueryOptions<
47 TQueryFnData,
48 TError,
49 TData,
50 TQueryData,
51 TQueryKey
52 >,
53 Observer: typeof QueryObserver,
54 queryClient?: QueryClient,
55): QueryObserverResult<TData, TError> {
56 if (process.env.NODE_ENV !== 'production') {
57 if (typeof options !== 'object' || Array.isArray(options)) {
58 throw new Error(
59 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object',
60 )
61 }
62 }
63​
64 const isRestoring = useIsRestoring()
65 const errorResetBoundary = useQueryErrorResetBoundary()
66 const client = useQueryClient(queryClient)
67 const defaultedOptions = client.defaultQueryOptions(options)
68​
69 const query = client
70 .getQueryCache()
71 .get<TQueryFnData, TError, TQueryData, TQueryKey>(
72 defaultedOptions.queryHash,
73 )
74​
75 if (process.env.NODE_ENV !== 'production') {
76 if (!defaultedOptions.queryFn) {
77 console.error(
78 `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`,
79 )
80 }
81 }
82​
83 const subscribed = options.subscribed !== false
84​
85 // Make sure results are optimistically set in fetching state before subscribing or updating options
86 defaultedOptions._optimisticResults = isRestoring
87 ? 'isRestoring'
88 : subscribed
89 ? 'optimistic'
90 : undefined
91​
92 ensureSuspenseTimers(defaultedOptions)
93 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
94 useClearResetErrorBoundary(errorResetBoundary)
95​
96 const [observer] = React.useState(
97 () =>
98 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
99 client,
100 defaultedOptions,
101 ),
102 )
103​
104 const reader = observer.createResultReader(defaultedOptions)
105​
106 // Suspend before registering external-store effects for this render.
107 if (shouldSuspend(defaultedOptions, reader.getSnapshot())) {
108 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
109 }
110​
111 const shouldSubscribe = !isRestoring && subscribed
112 const result = React.useSyncExternalStore(
113 React.useCallback(
114 (onStoreChange) => {
115 const unsubscribe = shouldSubscribe
116 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
117 : noop
118​
119 // Update result to make sure we did not miss any query updates
120 // between creating the observer and subscribing to it.
121 observer.updateResult()
122​
123 return unsubscribe
124 },
125 [observer, shouldSubscribe],
126 ),
127 reader.getSnapshot,
128 reader.getSnapshot,
129 )
130​
131 React.useEffect(() => {
132 reader.commit()
133 }, [reader])
134​
135 // Handle error boundary
136 if (
137 getHasError({
138 result,
139 errorResetBoundary,
140 throwOnError: defaultedOptions.throwOnError,
141 query,
142 suspense: defaultedOptions.suspense,
143 })
144 ) {
145 throw result.error
146 }
147​
148 // Handle result property usage tracking
149 return !defaultedOptions.notifyOnChangeProps
150 ? observer.trackResult(result)
151 : result