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

suspense.ts

70 lines2.2 KB

1import type { DefaultedQueryObserverOptions } from '@tanstack/query-core'
2import type { QueryObserver } from '@tanstack/query-core'
3import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'
4import type { QueryObserverResult } from '@tanstack/query-core'
5import type { QueryKey } from '@tanstack/query-core'
6​
7/**
8 * Ensures minimum staleTime and cacheTime values when suspense is enabled.
9 * Despite the name, this function guards both staleTime and cacheTime to prevent
10 * infinite re-render loops with synchronous queries.
11 *
12 * @deprecated in v5 - replaced by ensureSuspenseTimers
13 */
14export const ensureStaleTime = (
15 defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>,
16) => {
17 if (defaultedOptions.suspense) {
18 // Always set stale time when using suspense to prevent
19 // fetching again when directly mounting after suspending
20 if (typeof defaultedOptions.staleTime !== 'number') {
21 defaultedOptions.staleTime = 1000
22 }
23​
24 if (typeof defaultedOptions.cacheTime === 'number') {
25 defaultedOptions.cacheTime = Math.max(defaultedOptions.cacheTime, 1000)
26 }
27 }
29​
30export const willFetch = (
31 result: QueryObserverResult<any, any>,
32 isRestoring: boolean,
33) => result.isLoading && result.isFetching && !isRestoring
34​
35export const shouldSuspend = (
36 defaultedOptions:
37 | DefaultedQueryObserverOptions<any, any, any, any, any>
38 | undefined,
39 result: QueryObserverResult<any, any>,
40 isRestoring: boolean,
41) => defaultedOptions?.suspense && willFetch(result, isRestoring)
42​
43export const fetchOptimistic = <
44 TQueryFnData,
45 TError,
46 TData,
47 TQueryData,
48 TQueryKey extends QueryKey,
49>(
50 defaultedOptions: DefaultedQueryObserverOptions<
51 TQueryFnData,
52 TError,
53 TData,
54 TQueryData,
55 TQueryKey
56 >,
57 observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
58 errorResetBoundary: QueryErrorResetBoundaryValue,
59) =>
60 observer
61 .fetchOptimistic(defaultedOptions)
62 .then(({ data }) => {
63 defaultedOptions.onSuccess?.(data as TData)
64 defaultedOptions.onSettled?.(data, null)
65 })
66 .catch((error) => {
67 errorResetBoundary.clearReset()
68 defaultedOptions.onError?.(error)
69 defaultedOptions.onSettled?.(undefined, error)
70 })