Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/suspense-query-skip-token.md
Original file line number Diff line number Diff line change
@@ -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`.
15 changes: 13 additions & 2 deletions docs/framework/react/guides/suspense.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 2 additions & 3 deletions packages/preact-query/src/__tests__/queryOptions.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,13 @@ describe('queryOptions', () => {
expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf<unknown>()
})

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<number>()
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})

it('should allow undefined response in initialData', () => {
Expand Down
36 changes: 21 additions & 15 deletions packages/preact-query/src/__tests__/useSuspenseQuery.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>({
queryKey: createKey(),
queryFn: skipToken,
})
expectTypeOf(skipped.data).toEqualTypeOf<number | undefined>()

const result = useSuspenseQuery({
queryKey: createKey(),
queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
select: (data) => data.toString(),
})

expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
if (result.isSuccess) {
expectTypeOf(result.data).toEqualTypeOf<string>()
}
if (result.isPending) {
expectTypeOf(result.data).toEqualTypeOf<undefined>()
}
expectTypeOf(result).not.toHaveProperty('isPlaceholderData')
})

it('should not allow placeholderData, enabled or throwOnError props', () => {
Expand Down
128 changes: 54 additions & 74 deletions packages/preact-query/src/__tests__/useSuspenseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -894,135 +894,115 @@ 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<string>>(() =>
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 (
<Suspense fallback="loading">
<Page />
</Suspense>
<>
<button onClick={() => setReady(true)}>start</button>
<div>{result.data ?? `${result.status}/${result.fetchStatus}`}</div>
</>
)
}

renderWithClient(queryClient, <App />)

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 <div>count: {state.data}</div>
}

const rendered = renderWithClient(
queryClient,
<Suspense fallback="loading">
<Page />
</Suspense>,
)

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<string>({
queryKey: key,
queryFn: skipToken as any,
queryFn: skipToken,
})

return null
return <div>{data}</div>
}

renderWithClient(
const rendered = renderWithClient(
queryClient,
<Suspense fallback="loading">
<Page />
</Suspense>,
)
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 <div>count: {state.data}</div>
}

renderWithClient(
const rendered = renderWithClient(
queryClient,
<Suspense fallback="loading">
<Page />
</Suspense>,
)

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 () => {
Expand Down
9 changes: 4 additions & 5 deletions packages/preact-query/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
Expand Down
Loading
Loading