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

useBaseQuery.ts

138 lines4.0 KB

1'use client'
2import * as React from 'react'
3​
4import { notifyManager } from '@tanstack/query-core'
5import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
6import { useQueryClient } from './QueryClientProvider'
7import { useIsRestoring } from './isRestoring'
8import {
9 ensurePreventErrorBoundaryRetry,
10 getHasError,
11 useClearResetErrorBoundary,
12} from './errorBoundaryUtils'
13import { ensureStaleTime, fetchOptimistic, shouldSuspend } from './suspense'
14import type { UseBaseQueryOptions } from './types'
15import type {
16 QueryClient,
17 QueryKey,
18 QueryObserver,
19 QueryObserverResult,
20} from '@tanstack/query-core'
21​
22export function useBaseQuery<
23 TQueryFnData,
24 TError,
25 TData,
26 TQueryData,
27 TQueryKey extends QueryKey,
28>(
29 options: UseBaseQueryOptions<
30 TQueryFnData,
31 TError,
32 TData,
33 TQueryData,
34 TQueryKey
35 >,
36 Observer: typeof QueryObserver,
37 queryClient?: QueryClient,
38): QueryObserverResult<TData, TError> {
39 if (process.env.NODE_ENV !== 'production') {
40 if (typeof options !== 'object' || Array.isArray(options)) {
41 throw new Error(
42 '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',
43 )
44 }
45 }
46​
47 const client = useQueryClient(queryClient)
48 const isRestoring = useIsRestoring()
49 const errorResetBoundary = useQueryErrorResetBoundary()
50 const defaultedOptions = client.defaultQueryOptions(options)
51​
52 ;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
53 defaultedOptions,
54 )
55​
56 // Make sure results are optimistically set in fetching state before subscribing or updating options
57 defaultedOptions._optimisticResults = isRestoring
58 ? 'isRestoring'
59 : 'optimistic'
60​
61 ensureStaleTime(defaultedOptions)
62 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)
63​
64 useClearResetErrorBoundary(errorResetBoundary)
65​
66 const [observer] = React.useState(
67 () =>
68 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
69 client,
70 defaultedOptions,
71 ),
72 )
73​
74 const result = observer.getOptimisticResult(defaultedOptions)
75​
76 React.useSyncExternalStore(
77 React.useCallback(
78 (onStoreChange) => {
79 const unsubscribe = isRestoring
80 ? () => undefined
81 : observer.subscribe(notifyManager.batchCalls(onStoreChange))
82​
83 // Update result to make sure we did not miss any query updates
84 // between creating the observer and subscribing to it.
85 observer.updateResult()
86​
87 return unsubscribe
88 },
89 [observer, isRestoring],
90 ),
91 () => observer.getCurrentResult(),
92 () => observer.getCurrentResult(),
93 )
94​
95 React.useEffect(() => {
96 // Do not notify on updates because of changes in the options because
97 // these changes should already be reflected in the optimistic result.
98 observer.setOptions(defaultedOptions, { listeners: false })
99 }, [defaultedOptions, observer])
100​
101 // Handle suspense
102 if (shouldSuspend(defaultedOptions, result)) {
103 // Do the same thing as the effect right above because the effect won't run
104 // when we suspend but also, the component won't re-mount so our observer would
105 // be out of date.
106 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
107 }
108​
109 // Handle error boundary
110 if (
111 getHasError({
112 result,
113 errorResetBoundary,
114 throwOnError: defaultedOptions.throwOnError,
115 suspense: defaultedOptions.suspense,
116 query: client
117 .getQueryCache()
118 .get<
119 TQueryFnData,
120 TError,
121 TQueryData,
122 TQueryKey
123 >(defaultedOptions.queryHash),
124 })
125 ) {
126 throw result.error
127 }
128​
129 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
130 defaultedOptions,
131 result,
132 )
133​
134 // Handle result property usage tracking
135 return !defaultedOptions.notifyOnChangeProps
136 ? observer.trackResult(result)
137 : result