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

useBaseQuery.ts

151 lines4.1 KB

1import React from 'react'
2​
3import { QueryKey } from '../core'
4import { notifyManager } from '../core/notifyManager'
5import { QueryObserver } from '../core/queryObserver'
6import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
7import { useQueryClient } from './QueryClientProvider'
8import { UseBaseQueryOptions } from './types'
9import { shouldThrowError } from './utils'
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 mountedRef = React.useRef(false)
28 const [, forceUpdate] = React.useState(0)
29​
30 const queryClient = useQueryClient()
31 const errorResetBoundary = useQueryErrorResetBoundary()
32 const defaultedOptions = queryClient.defaultQueryObserverOptions(options)
33​
34 // Make sure results are optimistically set in fetching state before subscribing or updating options
35 defaultedOptions.optimisticResults = true
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 // Set cache time to 1 if the option has been set to 0
64 // when using suspense to prevent infinite loop of fetches
65 if (defaultedOptions.cacheTime === 0) {
66 defaultedOptions.cacheTime = 1
67 }
68 }
69​
70 if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
71 // Prevent retrying failed query if the error boundary has not been reset yet
72 if (!errorResetBoundary.isReset()) {
73 defaultedOptions.retryOnMount = false
74 }
75 }
76​
77 const [observer] = React.useState(
78 () =>
79 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
80 queryClient,
81 defaultedOptions
82 )
83 )
84​
85 let result = observer.getOptimisticResult(defaultedOptions)
86​
87 React.useEffect(() => {
88 mountedRef.current = true
89​
90 errorResetBoundary.clearReset()
91​
92 const unsubscribe = observer.subscribe(
93 notifyManager.batchCalls(() => {
94 if (mountedRef.current) {
95 forceUpdate(x => x + 1)
96 }
97 })
98 )
99​
100 // Update result to make sure we did not miss any query updates
101 // between creating the observer and subscribing to it.
102 observer.updateResult()
103​
104 return () => {
105 mountedRef.current = false
106 unsubscribe()
107 }
108 }, [errorResetBoundary, observer])
109​
110 React.useEffect(() => {
111 // Do not notify on updates because of changes in the options because
112 // these changes should already be reflected in the optimistic result.
113 observer.setOptions(defaultedOptions, { listeners: false })
114 }, [defaultedOptions, observer])
115​
116 // Handle suspense
117 if (defaultedOptions.suspense && result.isLoading) {
118 throw observer
119 .fetchOptimistic(defaultedOptions)
120 .then(({ data }) => {
121 defaultedOptions.onSuccess?.(data as TData)
122 defaultedOptions.onSettled?.(data, null)
123 })
124 .catch(error => {
125 errorResetBoundary.clearReset()
126 defaultedOptions.onError?.(error)
127 defaultedOptions.onSettled?.(undefined, error)
128 })
129 }
130​
131 // Handle error boundary
132 if (
133 result.isError &&
134 !errorResetBoundary.isReset() &&
135 !result.isFetching &&
136 shouldThrowError(
137 defaultedOptions.suspense,
138 defaultedOptions.useErrorBoundary,
139 [result.error, observer.getCurrentQuery()]
140 )
141 ) {
142 throw result.error
143 }
144​
145 // Handle result property usage tracking
146 if (defaultedOptions.notifyOnChangeProps === 'tracked') {
147 result = observer.trackResult(result, defaultedOptions)
148 }
149​
150 return result