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

internal.ts

186 lines7.0 KB

1// Shared internals for the binding hooks.
2import { shouldThrowError } from '@tanstack/query-core'
3import { use, useId, useRef } from 'octane'
4​
5// Derive a stable, distinct sub-slot from a wrapper's compiler-injected slot, so
6// a hook composing multiple base hooks gives each one its own identity. Tags are
7// namespaced per hook (e.g. ':oq:obs', ':ms:cb') to avoid cross-hook collisions.
8// Memoized: subSlot runs on EVERY hook call every render, and the naive form
9// pays a string concat + global symbol-registry lookup each time. The cache is
10// keyed by the slot symbol itself; the minted value is byte-identical to the
11// uncached Symbol.for result, so identity is preserved across HMR re-evals and
12// the per-package copies of this helper. Key universe is bounded: slots are
13// per-call-site module constants (never minted per render).
14const subSlotCache = new Map<symbol, Map<string, symbol>>()
15export function subSlot(
16 slot: symbol | undefined,
17 tag: string,
18): symbol | undefined {
19 if (slot === undefined) return undefined
20 let byTag = subSlotCache.get(slot)
21 if (byTag === undefined) subSlotCache.set(slot, (byTag = new Map()))
22 let sym = byTag.get(tag)
23 if (sym === undefined)
24 byTag.set(tag, (sym = Symbol.for((slot.description ?? '') + ':' + tag)))
25 return sym
27​
28// Split the compiler-injected trailing slot off a hook's runtime args, returning
29// the user args (everything before it) and the slot.
30export function splitSlot(args: Array<any>): [Array<any>, symbol | undefined] {
31 const tail = args[args.length - 1]
32 const slot = typeof tail === 'symbol' ? tail : undefined
33 return [slot !== undefined ? args.slice(0, -1) : args, slot]
35​
36// react-query's default suspense throwOnError: only throw if there's no data.
37export const defaultThrowOnError = (_error: unknown, query: any): boolean =>
38 query.state.data === undefined
39​
40// react-query's ensureSuspenseTimers: a suspense query gets a >=1s staleTime/gcTime
41// floor so it can't immediately refetch and re-trigger the fallback in a loop.
42export function ensureSuspenseTimers(defaultedOptions: any): void {
43 if (defaultedOptions.suspense) {
44 const MIN = 1000
45 const clamp = (value: any) =>
46 value === 'static' ? value : Math.max(value ?? MIN, MIN)
47 const orig = defaultedOptions.staleTime
48 defaultedOptions.staleTime =
49 typeof orig === 'function'
50 ? (...args: Array<any>) => clamp(orig(...args))
51 : clamp(orig)
52 if (typeof defaultedOptions.gcTime === 'number') {
53 defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN)
54 }
55 }
57​
58// prevent-error-boundary-retry: when a query opts into throwing, don't retry on
59// mount so an already-errored cached query re-throws immediately — UNLESS the
60// reset boundary has been reset, in which case a retry is expected.
61export function ensurePreventErrorBoundaryRetry(
62 options: any,
63 errorResetBoundary: { isReset: () => boolean },
64 query: any,
65): void {
66 const throwOnError =
67 query?.state.error && typeof options.throwOnError === 'function'
68 ? shouldThrowError(options.throwOnError, [query.state.error, query])
69 : options.throwOnError
70 if (
71 options.suspense ||
72 options.experimental_prefetchInRender ||
73 throwOnError
74 ) {
75 if (!errorResetBoundary.isReset()) {
76 options.retryOnMount = false
77 }
78 }
80​
81export const shouldSuspend = (defaultedOptions: any, result: any): boolean =>
82 defaultedOptions?.suspense && result.isPending
83​
84// A pending result that will actually fetch (not blocked by persistence restore).
85export const willFetch = (result: any, isRestoring: boolean): boolean =>
86 result.isLoading && result.isFetching && !isRestoring
87​
88// react-query's suspense fetch: kick the optimistic fetch and — CRUCIALLY — clear
89// the reset boundary on error. Without the clearReset, a boundary reset→retry
90// that fails AGAIN leaves `isReset()` true at replay, `getHasError` returns
91// false, and a suspense component falls through to render with undefined data
92// instead of re-throwing to the boundary. The returned promise resolves even on
93// error (the replay surfaces the error through the error-boundary throw).
94export function fetchOptimistic(
95 defaultedOptions: any,
96 observer: any,
97 errorResetBoundary: { clearReset: () => void },
98): Promise<unknown> {
99 return observer.fetchOptimistic(defaultedOptions).catch(() => {
100 errorResetBoundary.clearReset()
101 })
103​
104type SuspensePromise = PromiseLike<unknown> & {
105 status?: 'pending' | 'fulfilled' | 'rejected'
107​
108interface SuspensePromiseCache {
109 key: unknown
110 promise: SuspensePromise | undefined
112​
113// The server runtime accepts an explicit replay site key. Octane's universal
114// public type currently exposes only the client-compatible one-argument form.
115const useWithSiteKey = use as unknown as (
116 usable: PromiseLike<unknown>,
117 siteKey?: symbol | string,
118) => unknown
119​
120/**
121 * Suspend through a stable `use()` occurrence for one query-hook call site.
122 *
123 * `use()` tracks thenables by dynamic call order. A component with two
124 * sequential suspense queries initially reaches only the first query; when it
125 * resolves, the first query no longer needs to suspend and the second query is
126 * reached for the first time. If the first call simply skips `use()`, the
127 * second query takes its call-order position and replay reuses the first
128 * query's fulfilled promise, exposing the second query's still-pending result.
129 *
130 * Retain the promise that suspended this query hook and keep reading it after
131 * it settles. That reserves the query hook's dynamic call-order position on
132 * the client. Streaming SSR replays fresh hook passes, so an unconditional
133 * `useId()` gives each query-hook instance a deterministic server replay key,
134 * including when a custom hook is called more than once. A new query key or
135 * retry replaces a settled promise; re-renders during the same pending fetch
136 * reuse the in-flight promise.
137 */
138export function useSuspensePromise(
139 needsSuspense: boolean,
140 key: unknown,
141 createPromise: () => PromiseLike<unknown>,
142 slot: symbol | undefined,
143): void {
144 const siteKey = useId(subSlot(slot, 'id'))
145 const cache = useRef<SuspensePromiseCache>(
146 { key: undefined, promise: undefined },
147 slot,
148 ).current
149 if (
150 needsSuspense &&
151 (cache.promise === undefined ||
152 cache.key !== key ||
153 cache.promise.status !== 'pending')
154 ) {
155 cache.key = key
156 cache.promise = createPromise()
157 }
158 if (cache.promise !== undefined) {
159 useWithSiteKey(cache.promise, siteKey)
160 }
162​
163// react-query's getHasError: only throw if the query errored, the boundary isn't
164// reset, the query isn't refetching, and the options opt into throwing.
165export function getHasError({
166 result,
167 errorResetBoundary,
168 throwOnError,
169 query,
170 suspense,
171}: {
172 result: any
173 errorResetBoundary: { isReset: () => boolean }
174 throwOnError: any
175 query: any
176 suspense: any
177}): boolean {
178 return (
179 result.isError &&
180 !errorResetBoundary.isReset() &&
181 !result.isFetching &&
182 query &&
183 ((suspense && result.data === undefined) ||
184 shouldThrowError(throwOnError, [result.error, query]))
185 )