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

useBaseQuery.ts

137 lines3.7 KB

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