From b74dedb05601ab79d729e168c9646fe04e5f2910 Mon Sep 17 00:00:00 2001 From: TkDodo Date: Sun, 22 Nov 2026 22:08:06 +0100 Subject: [PATCH] feat: support skipToken in useSuspenseQuery --- .changeset/suspense-query-skip-token.md | 6 + docs/framework/react/guides/suspense.md | 15 +- .../src/__tests__/queryOptions.test-d.tsx | 5 +- .../src/__tests__/useSuspenseQuery.test-d.tsx | 36 +++-- .../src/__tests__/useSuspenseQuery.test.tsx | 128 ++++++++---------- packages/preact-query/src/types.ts | 9 +- packages/preact-query/src/useSuspenseQuery.ts | 87 +++++++++--- .../src/__tests__/queryOptions.test-d.tsx | 5 +- .../src/__tests__/useSuspenseQuery.test-d.tsx | 35 +++-- .../src/__tests__/useSuspenseQuery.test.tsx | 116 +++++++--------- packages/react-query/src/types.ts | 9 +- packages/react-query/src/useSuspenseQuery.ts | 86 +++++++++--- 12 files changed, 312 insertions(+), 225 deletions(-) create mode 100644 .changeset/suspense-query-skip-token.md diff --git a/.changeset/suspense-query-skip-token.md b/.changeset/suspense-query-skip-token.md new file mode 100644 index 00000000000..5ae8daf90dd --- /dev/null +++ b/.changeset/suspense-query-skip-token.md @@ -0,0 +1,6 @@ +--- +'@tanstack/react-query': minor +'@tanstack/preact-query': minor +--- + +Add `skipToken` support to `useSuspenseQuery`. When `queryFn` can be `skipToken`, the result can have undefined data. Calls with a regular query function still return data of type `TData`. diff --git a/docs/framework/react/guides/suspense.md b/docs/framework/react/guides/suspense.md index 2e7e52aeeaa..36924a5e224 100644 --- a/docs/framework/react/guides/suspense.md +++ b/docs/framework/react/guides/suspense.md @@ -24,9 +24,20 @@ import { useSuspenseQuery } from '@tanstack/react-query' const { data } = useSuspenseQuery({ queryKey, queryFn }) ``` -This works nicely in TypeScript, because `data` is guaranteed to be defined (as errors and loading states are handled by Suspense- and ErrorBoundaries). +When `queryFn` cannot be `skipToken`, TypeScript gives `data` the type `TData`. Suspense and error boundaries handle loading and initial fetch errors. -On the flip side, you therefore can't conditionally enable / disable the Query. This generally shouldn't be necessary for dependent Queries because with suspense, all your Queries inside one component are fetched in serial. +To skip a single Query, pass `skipToken` as its `queryFn`. A skipped Query can still read cached data. It does not fetch automatically or suspend. If `queryFn` can be `skipToken`, check `data` before using it because the cache can be empty. + +```tsx +import { skipToken, useSuspenseQuery } from '@tanstack/react-query' + +const { data } = useSuspenseQuery({ + queryKey: ['post', postId], + queryFn: postId === undefined ? skipToken : () => fetchPost(postId), +}) +``` + +For dependent Queries in the same component, each Query that suspends completes before the next hook runs. `placeholderData` is supported. When it returns defined data, the Query renders that data in `success` state and fetches the full data in the background without showing the Suspense fallback. This is useful when a detail Query can show preview data from a cached list Query. diff --git a/packages/preact-query/src/__tests__/queryOptions.test-d.tsx b/packages/preact-query/src/__tests__/queryOptions.test-d.tsx index dcd41cf2589..cb8923efcf5 100644 --- a/packages/preact-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/preact-query/src/__tests__/queryOptions.test-d.tsx @@ -225,14 +225,13 @@ describe('queryOptions', () => { expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() }) - it('should throw a type error when using queryFn with skipToken in a suspense query', () => { + it('should allow undefined data when passing options with skipToken to useSuspenseQuery', () => { const options = queryOptions({ queryKey: createKey(), queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), }) - // @ts-expect-error TS2345 const { data } = useSuspenseQuery(options) - expectTypeOf(data).toEqualTypeOf() + expectTypeOf(data).toEqualTypeOf() }) it('should allow undefined response in initialData', () => { diff --git a/packages/preact-query/src/__tests__/useSuspenseQuery.test-d.tsx b/packages/preact-query/src/__tests__/useSuspenseQuery.test-d.tsx index 98feeec5937..bc2bf049555 100644 --- a/packages/preact-query/src/__tests__/useSuspenseQuery.test-d.tsx +++ b/packages/preact-query/src/__tests__/useSuspenseQuery.test-d.tsx @@ -22,21 +22,27 @@ describe('useSuspenseQuery', () => { expectTypeOf(status).toEqualTypeOf<'error' | 'success'>() }) - it('should not allow skipToken in queryFn', () => { - assertType( - useSuspenseQuery({ - queryKey: createKey(), - // @ts-expect-error - queryFn: skipToken, - }), - ) - assertType( - useSuspenseQuery({ - queryKey: createKey(), - // @ts-expect-error - queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - }), - ) + it('should allow undefined data when queryFn can be skipToken', () => { + const skipped = useSuspenseQuery({ + queryKey: createKey(), + queryFn: skipToken, + }) + expectTypeOf(skipped.data).toEqualTypeOf() + + const result = useSuspenseQuery({ + queryKey: createKey(), + queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), + select: (data) => data.toString(), + }) + + expectTypeOf(result.data).toEqualTypeOf() + if (result.isSuccess) { + expectTypeOf(result.data).toEqualTypeOf() + } + if (result.isPending) { + expectTypeOf(result.data).toEqualTypeOf() + } + expectTypeOf(result).not.toHaveProperty('isPlaceholderData') }) it('should not allow placeholderData, enabled or throwOnError props', () => { diff --git a/packages/preact-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/preact-query/src/__tests__/useSuspenseQuery.test.tsx index 5669f3a17e5..90b30576b2c 100644 --- a/packages/preact-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/preact-query/src/__tests__/useSuspenseQuery.test.tsx @@ -894,51 +894,27 @@ describe('useSuspenseQuery', () => { expect(rendered.getByText('data: 2')).toBeInTheDocument() }) - it('should log an error when skipToken is passed as queryFn', () => { - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockImplementation(() => {}) + it('should render without fetching until skipToken is replaced by a query function', async () => { const key = createKey() + const queryFn = vi.fn<() => Promise>(() => + sleep(10).then(() => 'fetched'), + ) function Page() { - useSuspenseQuery({ + const [ready, setReady] = useState(false) + const result = useSuspenseQuery({ queryKey: key, - // @ts-expect-error - queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5), + queryFn: ready ? queryFn : skipToken, }) - return null - } - - function App() { return ( - - - + <> + +
{result.data ?? `${result.status}/${result.fetchStatus}`}
+ ) } - renderWithClient(queryClient, ) - - expect(consoleErrorMock).toHaveBeenCalledWith( - 'skipToken is not allowed for useSuspenseQuery', - ) - }) - - it('should properly refresh data when refetchInterval is set', async () => { - const key = createKey() - let count = 0 - - function Page() { - const state = useSuspenseQuery({ - queryKey: key, - queryFn: () => sleep(10).then(() => ++count), - refetchInterval: 10, - }) - - return
count: {state.data}
- } - const rendered = renderWithClient( queryClient, @@ -946,83 +922,87 @@ describe('useSuspenseQuery', () => { , ) + expect(rendered.getByText('pending/idle')).toBeInTheDocument() + expect(rendered.queryByText('loading')).not.toBeInTheDocument() + expect(queryFn).not.toHaveBeenCalled() + + await act(() => { + fireEvent.click(rendered.getByRole('button', { name: 'start' })) + }) + expect(rendered.getByText('loading')).toBeInTheDocument() await act(async () => { await vi.advanceTimersByTimeAsync(10) }) - expect(rendered.getByText('count: 1')).toBeInTheDocument() - await act(async () => { - await vi.advanceTimersByTimeAsync(21) - }) - expect(rendered.getByText('count: 2')).toBeInTheDocument() - await act(async () => { - await vi.advanceTimersByTimeAsync(21) - }) - expect(rendered.getByText('count: 3')).toBeInTheDocument() - - expect(count).toBeGreaterThanOrEqual(3) + expect(rendered.getByText('fetched')).toBeInTheDocument() + expect(queryFn).toHaveBeenCalledTimes(1) }) - it('should log an error when skipToken is used in development environment', () => { - const envCopy = process.env.NODE_ENV - process.env.NODE_ENV = 'development' - - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockReturnValue(undefined) + it('should observe cached data while queryFn is skipToken', async () => { const key = createKey() + queryClient.setQueryData(key, 'cached') function Page() { - useSuspenseQuery({ + const { data } = useSuspenseQuery({ queryKey: key, - queryFn: skipToken as any, + queryFn: skipToken, }) - return null + return
{data}
} - renderWithClient( + const rendered = renderWithClient( queryClient, , ) + expect(rendered.getByText('cached')).toBeInTheDocument() - expect(consoleErrorMock).toHaveBeenCalledWith( - 'skipToken is not allowed for useSuspenseQuery', - ) + await act(async () => { + queryClient.setQueryData(key, 'updated') + await vi.advanceTimersByTimeAsync(0) + }) - process.env.NODE_ENV = envCopy + expect(rendered.getByText('updated')).toBeInTheDocument() }) - it('should not log an error when skipToken is used in production environment', () => { - const envCopy = process.env.NODE_ENV - process.env.NODE_ENV = 'production' - - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockReturnValue(undefined) + it('should properly refresh data when refetchInterval is set', async () => { const key = createKey() + let count = 0 function Page() { - useSuspenseQuery({ + const state = useSuspenseQuery({ queryKey: key, - queryFn: skipToken as any, + queryFn: () => sleep(10).then(() => ++count), + refetchInterval: 10, }) - return null + return
count: {state.data}
} - renderWithClient( + const rendered = renderWithClient( queryClient, , ) - expect(consoleErrorMock).not.toHaveBeenCalled() + expect(rendered.getByText('loading')).toBeInTheDocument() + await act(async () => { + await vi.advanceTimersByTimeAsync(10) + }) + expect(rendered.getByText('count: 1')).toBeInTheDocument() + await act(async () => { + await vi.advanceTimersByTimeAsync(21) + }) + expect(rendered.getByText('count: 2')).toBeInTheDocument() + await act(async () => { + await vi.advanceTimersByTimeAsync(21) + }) + expect(rendered.getByText('count: 3')).toBeInTheDocument() - process.env.NODE_ENV = envCopy + expect(count).toBeGreaterThanOrEqual(3) }) it('should release suspense when setQueryData is called while fetch is in-flight', async () => { diff --git a/packages/preact-query/src/types.ts b/packages/preact-query/src/types.ts index a9fd8822693..3e38f7f0ea3 100644 --- a/packages/preact-query/src/types.ts +++ b/packages/preact-query/src/types.ts @@ -177,9 +177,9 @@ export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< any > /** - * The options accepted by `useSuspenseQuery`. Same as {@link UseQueryOptions}, minus `enabled`, `throwOnError`, - * and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so those options - * don't apply. + * Options for a `useSuspenseQuery` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError`, `enabled`, and `placeholderData`. + * Use the other overload for a query function that can be `skipToken`. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no @@ -196,8 +196,7 @@ export interface UseSuspenseQueryOptions< 'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData' > { /** - * `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function - * must always be provided, unless a default query function has been defined. + * A query function. Omit this option to use the client's default query function. */ queryFn?: Exclude< UseQueryOptions['queryFn'], diff --git a/packages/preact-query/src/useSuspenseQuery.ts b/packages/preact-query/src/useSuspenseQuery.ts index 0e27713bea0..9af4dd0d2ea 100644 --- a/packages/preact-query/src/useSuspenseQuery.ts +++ b/packages/preact-query/src/useSuspenseQuery.ts @@ -1,19 +1,38 @@ import { QueryObserver, skipToken } from '@tanstack/query-core' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' -import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core' -import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' +import type { + DefaultError, + DistributiveOmit, + OmitKeyof, + QueryClient, + QueryKey, +} from '@tanstack/query-core' +import type { + UseQueryOptions, + UseQueryResult, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' | 'placeholderData' +> /** - * The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and - * `placeholderData`. + * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError`, `enabled`, and `placeholderData`. * * Caveat: cancellation does not work. - * @param options - The {@link UseSuspenseQueryOptions} to use — the same options as `useQuery`, minus the ones listed above. + * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. - * @returns The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData` - * is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + * @returns A result with data of type `TData` and a status of `success` or `error`. * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they @@ -97,22 +116,56 @@ export function useSuspenseQuery< >( options: UseSuspenseQueryOptions, queryClient?: QueryClient, -): UseSuspenseQueryResult { - if (process.env.NODE_ENV !== 'production') { - if ((options.queryFn as any) === skipToken) { - console.error('skipToken is not allowed for useSuspenseQuery') - } - } +): UseSuspenseQueryResult + +/** + * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data + * but does not fetch automatically, suspend, or throw a query error to the nearest error boundary. + * Pass a query function to resume normal Suspense behavior. + * @param options - Options for a query that can be skipped. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns A result whose data can be undefined and whose status can be `pending`. + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): DistributiveOmit, 'isPlaceholderData'> + +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): DistributiveOmit, 'isPlaceholderData'> { + const skipped = options.queryFn === skipToken return useBaseQuery( { ...options, - enabled: true, - throwOnError: defaultThrowOnError, + enabled: !skipped, + throwOnError: skipped ? false : defaultThrowOnError, placeholderData: undefined, }, QueryObserver, queryClient, - suspenseQueryPolicy, - ) as UseSuspenseQueryResult + skipped ? undefined : suspenseQueryPolicy, + ) } diff --git a/packages/react-query/src/__tests__/queryOptions.test-d.tsx b/packages/react-query/src/__tests__/queryOptions.test-d.tsx index 922afcee175..435d85b46cb 100644 --- a/packages/react-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/queryOptions.test-d.tsx @@ -258,14 +258,13 @@ describe('queryOptions', () => { expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() }) - it('should throw a type error when using queryFn with skipToken in a suspense query', () => { + it('should allow undefined data when passing options with skipToken to useSuspenseQuery', () => { const options = queryOptions({ queryKey: createKey(), queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), }) - // @ts-expect-error TS2345 const { data } = useSuspenseQuery(options) - expectTypeOf(data).toEqualTypeOf() + expectTypeOf(data).toEqualTypeOf() }) it('should allow undefined response in initialData', () => { diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx index 84f6bc7e570..d2935226a44 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx @@ -22,21 +22,26 @@ describe('useSuspenseQuery', () => { expectTypeOf(status).toEqualTypeOf<'error' | 'success'>() }) - it('should not allow skipToken in queryFn', () => { - assertType( - useSuspenseQuery({ - queryKey: createKey(), - // @ts-expect-error - queryFn: skipToken, - }), - ) - assertType( - useSuspenseQuery({ - queryKey: createKey(), - // @ts-expect-error - queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - }), - ) + it('should allow undefined data when queryFn can be skipToken', () => { + const skipped = useSuspenseQuery({ + queryKey: createKey(), + queryFn: skipToken, + }) + expectTypeOf(skipped.data).toEqualTypeOf() + + const result = useSuspenseQuery({ + queryKey: createKey(), + queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), + select: (data) => data.toString(), + }) + + expectTypeOf(result.data).toEqualTypeOf() + if (result.isSuccess) { + expectTypeOf(result.data).toEqualTypeOf() + } + if (result.isPending) { + expectTypeOf(result.data).toEqualTypeOf() + } }) it('should allow placeholderData', () => { diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx index dde40112782..69235dbb683 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx @@ -1114,114 +1114,92 @@ describe('useSuspenseQuery', () => { consoleMock.mockRestore() }) - it('should log an error when skipToken is passed as queryFn', async () => { - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockImplementation(() => {}) + it('should render without fetching until skipToken is replaced by a query function', async () => { const key = createKey() + const queryFn = vi.fn<() => Promise>(() => + sleep(10).then(() => 'fetched'), + ) function Page() { - useSuspenseQuery({ + const [ready, setReady] = React.useState(false) + const result = useSuspenseQuery({ queryKey: key, - // @ts-expect-error - queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5), + queryFn: ready ? queryFn : skipToken, }) - return null - } - - function App() { return ( - - - + <> + +
{result.data ?? `${result.status}/${result.fetchStatus}`}
+ ) } - await renderWithSuspense(queryClient, ) - - expect(consoleErrorMock).toHaveBeenCalledWith( - 'skipToken is not allowed for useSuspenseQuery', - ) - }) - - it('should properly refresh data when refetchInterval is set', async () => { - const key = createKey() - let count = 0 - - function Page() { - const state = useSuspenseQuery({ - queryKey: key, - queryFn: () => sleep(10).then(() => ++count), - refetchInterval: 10, - }) + const rendered = await renderWithSuspense(queryClient, ) - return
count: {state.data}
- } + expect(rendered.getByText('pending/idle')).toBeInTheDocument() + expect(rendered.queryByText('loading')).not.toBeInTheDocument() + expect(queryFn).not.toHaveBeenCalled() - const rendered = await renderWithSuspense(queryClient, ) + await act(() => { + fireEvent.click(rendered.getByRole('button', { name: 'start' })) + }) expect(rendered.getByText('loading')).toBeInTheDocument() await act(() => vi.advanceTimersByTimeAsync(10)) - expect(rendered.getByText('count: 1')).toBeInTheDocument() - await vi.advanceTimersByTimeAsync(21) - expect(rendered.getByText('count: 2')).toBeInTheDocument() - await vi.advanceTimersByTimeAsync(21) - expect(rendered.getByText('count: 3')).toBeInTheDocument() - - expect(count).toBeGreaterThanOrEqual(3) + expect(rendered.getByText('fetched')).toBeInTheDocument() + expect(queryFn).toHaveBeenCalledTimes(1) }) - it('should log an error when skipToken is used in development environment', async () => { - const envCopy = process.env.NODE_ENV - process.env.NODE_ENV = 'development' - - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockReturnValue(undefined) + it('should observe cached data while queryFn is skipToken', async () => { const key = createKey() + queryClient.setQueryData(key, 'cached') function Page() { - useSuspenseQuery({ + const { data } = useSuspenseQuery({ queryKey: key, - queryFn: skipToken as any, + queryFn: skipToken, }) - return null + return
{data}
} - await renderWithSuspense(queryClient, ) + const rendered = await renderWithSuspense(queryClient, ) + expect(rendered.getByText('cached')).toBeInTheDocument() - expect(consoleErrorMock).toHaveBeenCalledWith( - 'skipToken is not allowed for useSuspenseQuery', - ) + await act(async () => { + queryClient.setQueryData(key, 'updated') + await vi.advanceTimersByTimeAsync(0) + }) - process.env.NODE_ENV = envCopy + expect(rendered.getByText('updated')).toBeInTheDocument() }) - it('should not log an error when skipToken is used in production environment', async () => { - const envCopy = process.env.NODE_ENV - process.env.NODE_ENV = 'production' - - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockReturnValue(undefined) + it('should properly refresh data when refetchInterval is set', async () => { const key = createKey() + let count = 0 function Page() { - useSuspenseQuery({ + const state = useSuspenseQuery({ queryKey: key, - queryFn: skipToken as any, + queryFn: () => sleep(10).then(() => ++count), + refetchInterval: 10, }) - return null + return
count: {state.data}
} - await renderWithSuspense(queryClient, ) + const rendered = await renderWithSuspense(queryClient, ) - expect(consoleErrorMock).not.toHaveBeenCalled() + expect(rendered.getByText('loading')).toBeInTheDocument() + await act(() => vi.advanceTimersByTimeAsync(10)) + expect(rendered.getByText('count: 1')).toBeInTheDocument() + await vi.advanceTimersByTimeAsync(21) + expect(rendered.getByText('count: 2')).toBeInTheDocument() + await vi.advanceTimersByTimeAsync(21) + expect(rendered.getByText('count: 3')).toBeInTheDocument() - process.env.NODE_ENV = envCopy + expect(count).toBeGreaterThanOrEqual(3) }) it('should release suspense when setQueryData is called while fetch is in-flight', async () => { diff --git a/packages/react-query/src/types.ts b/packages/react-query/src/types.ts index 09e0a6b822e..a4b0a4cf282 100644 --- a/packages/react-query/src/types.ts +++ b/packages/react-query/src/types.ts @@ -180,9 +180,9 @@ export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< any > /** - * The options accepted by `useSuspenseQuery`. Same as {@link UseQueryOptions}, minus `enabled`, `throwOnError`, - * and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so those options - * don't apply. + * Options for a `useSuspenseQuery` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError` and `enabled`. + * Use the other overload for a query function that can be `skipToken`. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no @@ -199,8 +199,7 @@ export interface UseSuspenseQueryOptions< 'queryFn' | 'enabled' | 'throwOnError' > { /** - * `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function - * must always be provided, unless a default query function has been defined. + * A query function. Omit this option to use the client's default query function. */ queryFn?: Exclude< UseQueryOptions['queryFn'], diff --git a/packages/react-query/src/useSuspenseQuery.ts b/packages/react-query/src/useSuspenseQuery.ts index 4c08da1e360..dda6edbcf54 100644 --- a/packages/react-query/src/useSuspenseQuery.ts +++ b/packages/react-query/src/useSuspenseQuery.ts @@ -2,19 +2,37 @@ import { QueryObserver, skipToken } from '@tanstack/query-core' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' -import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core' -import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' +import type { + DefaultError, + OmitKeyof, + QueryClient, + QueryKey, +} from '@tanstack/query-core' +import type { + UseQueryOptions, + UseQueryResult, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' +> /** - * The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and - * `placeholderData` — and `queryFn` may not be `skipToken`, since Suspense hooks can't render a "disabled" state. + * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError` and `enabled`. * * Caveat: cancellation does not work. - * @param options - The {@link UseSuspenseQueryOptions} to use — the same options as `useQuery`, minus the ones listed above. + * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. - * @returns The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData` - * is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + * @returns A result with data of type `TData` and a status of `success` or `error`. * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they @@ -78,21 +96,55 @@ export function useSuspenseQuery< >( options: UseSuspenseQueryOptions, queryClient?: QueryClient, -): UseSuspenseQueryResult { - if (process.env.NODE_ENV !== 'production') { - if ((options.queryFn as any) === skipToken) { - console.error('skipToken is not allowed for useSuspenseQuery') - } - } +): UseSuspenseQueryResult + +/** + * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data + * but does not fetch automatically, suspend, or throw a query error to the nearest error boundary. + * Pass a query function to resume normal Suspense behavior. + * @param options - Options for a query that can be skipped. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns A result whose data can be undefined and whose status can be `pending`. + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult + +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult { + const skipped = options.queryFn === skipToken return useBaseQuery( { ...options, - enabled: true, - throwOnError: defaultThrowOnError, + enabled: !skipped, + throwOnError: skipped ? false : defaultThrowOnError, }, QueryObserver, queryClient, - suspenseQueryPolicy, - ) as UseSuspenseQueryResult + skipped ? undefined : suspenseQueryPolicy, + ) }