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

useBaseQuery.ts

140 lines3.8 KB

1import * as React from 'react'
2import { useSyncExternalStore } from './useSyncExternalStore'
3​
4import { QueryKey, notifyManager, QueryObserver } from '@tanstack/query-core'
5import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
6import { useQueryClient } from './QueryClientProvider'
7import { UseBaseQueryOptions } from './types'
8import { shouldThrowError } from './utils'
9import { useIsRestoring } from './isRestoring'
10​
11export function useBaseQuery<
12 TQueryFnData,
13 TError,
14 TData,
15 TQueryData,
16 TQueryKey extends QueryKey,
17>(
18 options: UseBaseQueryOptions<
19 TQueryFnData,
20 TError,
21 TData,
22 TQueryData,
23 TQueryKey
24 >,
25 Observer: typeof QueryObserver,
26) {
27 const queryClient = useQueryClient({ context: options.context })
28 const isRestoring = useIsRestoring()
29 const errorResetBoundary = useQueryErrorResetBoundary()
30 const defaultedOptions = queryClient.defaultQueryOptions(options)
31​
32 // Make sure results are optimistically set in fetching state before subscribing or updating options
33 defaultedOptions._optimisticResults = isRestoring
34 ? 'isRestoring'
35 : 'optimistic'
36​
37 // Include callbacks in batch renders
38 if (defaultedOptions.onError) {
39 defaultedOptions.onError = notifyManager.batchCalls(
40 defaultedOptions.onError,
41 )
42 }
43​
44 if (defaultedOptions.onSuccess) {
45 defaultedOptions.onSuccess = notifyManager.batchCalls(
46 defaultedOptions.onSuccess,
47 )
48 }
49​
50 if (defaultedOptions.onSettled) {
51 defaultedOptions.onSettled = notifyManager.batchCalls(
52 defaultedOptions.onSettled,
53 )
54 }
55​
56 if (defaultedOptions.suspense) {
57 // Always set stale time when using suspense to prevent
58 // fetching again when directly mounting after suspending
59 if (typeof defaultedOptions.staleTime !== 'number') {
60 defaultedOptions.staleTime = 1000
61 }
62 }
63​
64 if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
65 // Prevent retrying failed query if the error boundary has not been reset yet
66 if (!errorResetBoundary.isReset()) {
67 defaultedOptions.retryOnMount = false
68 }
69 }
70​
71 const [observer] = React.useState(
72 () =>
73 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
74 queryClient,
75 defaultedOptions,
76 ),
77 )
78​
79 const result = observer.getOptimisticResult(defaultedOptions)
80​
81 useSyncExternalStore(
82 React.useCallback(
83 (onStoreChange) =>
84 isRestoring
85 ? () => undefined
86 : observer.subscribe(notifyManager.batchCalls(onStoreChange)),
87 [observer, isRestoring],
88 ),
89 () => observer.getCurrentResult(),
90 () => observer.getCurrentResult(),
91 )
92​
93 React.useEffect(() => {
94 errorResetBoundary.clearReset()
95 }, [errorResetBoundary])
96​
97 React.useEffect(() => {
98 // Do not notify on updates because of changes in the options because
99 // these changes should already be reflected in the optimistic result.
100 observer.setOptions(defaultedOptions, { listeners: false })
101 }, [defaultedOptions, observer])
102​
103 // Handle suspense
104 if (
105 defaultedOptions.suspense &&
106 result.isLoading &&
107 result.isFetching &&
108 !isRestoring
109 ) {
110 throw observer
111 .fetchOptimistic(defaultedOptions)
112 .then(({ data }) => {
113 defaultedOptions.onSuccess?.(data as TData)
114 defaultedOptions.onSettled?.(data, null)
115 })
116 .catch((error) => {
117 errorResetBoundary.clearReset()
118 defaultedOptions.onError?.(error)
119 defaultedOptions.onSettled?.(undefined, error)
120 })
121 }
122​
123 // Handle error boundary
124 if (
125 result.isError &&
126 !errorResetBoundary.isReset() &&
127 !result.isFetching &&
128 shouldThrowError(defaultedOptions.useErrorBoundary, [
129 result.error,
130 observer.getCurrentQuery(),
131 ])
132 ) {
133 throw result.error
134 }
135​
136 // Handle result property usage tracking
137 return !defaultedOptions.notifyOnChangeProps
138 ? observer.trackResult(result)
139 : result