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

useBaseQuery.ts

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