Skip to content
Merged
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/v6-suspense-boundary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/react-query': major
'@tanstack/preact-query': major
---

Load render-time Suspense code through `useSuspenseQuery`, `useSuspenseInfiniteQuery`, and `useSuspenseQueries`. If JavaScript code passes `suspense: true` to an ordinary query hook or through client defaults, migrate that call to the corresponding Suspense hook.
66 changes: 65 additions & 1 deletion packages/preact-query/src/suspense.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { QueryObserver } from '@tanstack/query-core'
import { use } from 'preact/compat'
import type {
DefaultError,
DefaultedQueryObserverOptions,
Query,
QueryClient,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'
Expand Down Expand Up @@ -121,3 +123,65 @@ export const getSuspensePromise = <
})
return promise
}

type SuspenseOptions = DefaultedQueryObserverOptions<any, any, any, any, any>
type SuspenseResult = QueryObserverResult<any, any>
type SnapshotReader<T> = { getSnapshot: () => T }

const useReadSuspenseQuery = (
defaultedOptions: SuspenseOptions,
reader: SnapshotReader<SuspenseResult>,
observer: QueryObserver<any, any, any, any, any>,
client: QueryClient,
errorResetBoundary: QueryErrorResetBoundaryValue,
) => {
// Suspend before registering external-store effects for this render.
if (shouldSuspend(defaultedOptions, reader.getSnapshot())) {
const suspenseQuery = client.getQueryCache().build(client, defaultedOptions)
use(
getSuspensePromise(
defaultedOptions,
observer,
errorResetBoundary,
suspenseQuery,
),
)
}
}

/** Supplies Suspense behavior for one query. */
export const suspenseQueryPolicy = {
prepare: ensureSuspenseTimers,
readQuery: useReadSuspenseQuery,
}

const useReadSuspenseQueries = (
defaultedQueries: Array<SuspenseOptions>,
reader: SnapshotReader<Array<SuspenseResult>>,
client: QueryClient,
errorResetBoundary: QueryErrorResetBoundaryValue,
) => {
const suspensePromises = reader.getSnapshot().flatMap((result, index) => {
const options = defaultedQueries[index]
if (!options || !shouldSuspend(options, result)) return []

const observer = new QueryObserver(client, options)
return getSuspensePromise(
options,
observer,
errorResetBoundary,
observer.getCurrentQuery(),
)
})

if (suspensePromises.length > 0) {
// Keep the boundary suspended until every pending query has settled.
use(Promise.all(suspensePromises))
}
}

/** Supplies Suspense behavior for parallel queries. */
export const suspenseQueriesPolicy = {
prepare: ensureSuspenseTimers,
readQueries: useReadSuspenseQueries,
}
35 changes: 15 additions & 20 deletions packages/preact-query/src/useBaseQuery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { noop, notifyManager } from '@tanstack/query-core'
import { use } from 'preact/compat'
import { useCallback, useEffect, useState } from 'preact/hooks'
import { useIsRestoring } from './IsRestoringProvider'
import { useQueryClient } from './QueryClientProvider'
Expand All @@ -9,18 +8,14 @@ import {
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'
import {
ensureSuspenseTimers,
getSuspensePromise,
shouldSuspend,
} from './suspense'
import { useSyncExternalStore } from './utils'
import type {
QueryClient,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { suspenseQueryPolicy } from './suspense'
import type { UseBaseQueryOptions } from './types'

/**
Expand All @@ -31,6 +26,7 @@ import type { UseBaseQueryOptions } from './types'
* `InfiniteQueryObserver`).
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
* context will be used.
* @param suspense - Render policy used by the dedicated Suspense hooks.
* @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is
* set.
* @throws {Error} If `options` is not an object (outside production), or the query error when it should be
Expand All @@ -52,6 +48,7 @@ export function useBaseQuery<
>,
Observer: typeof QueryObserver,
queryClient?: QueryClient,
suspense?: typeof suspenseQueryPolicy,
): QueryObserverResult<TData, TError> {
if (process.env.NODE_ENV !== 'production') {
if (typeof options !== 'object' || Array.isArray(options)) {
Expand All @@ -64,7 +61,10 @@ export function useBaseQuery<
const isRestoring = useIsRestoring()
const errorResetBoundary = useQueryErrorResetBoundary()
const client = useQueryClient(queryClient)
const defaultedOptions = client.defaultQueryOptions(options)
const defaultedOptions = client.defaultQueryOptions({
...options,
suspense: !!suspense,
})

const query = client
.getQueryCache()
Expand All @@ -89,7 +89,7 @@ export function useBaseQuery<
? 'optimistic'
: undefined

ensureSuspenseTimers(defaultedOptions)
suspense?.prepare(defaultedOptions)
ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)

useClearResetErrorBoundary(errorResetBoundary)
Expand All @@ -104,18 +104,13 @@ export function useBaseQuery<

const reader = observer.createResultReader(defaultedOptions)

// Suspend before registering external-store effects for this render.
if (shouldSuspend(defaultedOptions, reader.getSnapshot())) {
const suspenseQuery = client.getQueryCache().build(client, defaultedOptions)
use(
getSuspensePromise(
defaultedOptions,
observer,
errorResetBoundary,
suspenseQuery,
),
)
}
suspense?.readQuery(
defaultedOptions,
reader,
observer,
client,
errorResetBoundary,
)

useEffect(() => {
reader.commit()
Expand Down
119 changes: 52 additions & 67 deletions packages/preact-query/src/useQueries.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import {
QueriesObserver,
QueryObserver,
noop,
notifyManager,
} from '@tanstack/query-core'
import { use } from 'preact/compat'
import { QueriesObserver, noop, notifyManager } from '@tanstack/query-core'
import { useCallback, useEffect, useMemo, useState } from 'preact/hooks'
import { useIsRestoring } from './IsRestoringProvider'
import { useQueryClient } from './QueryClientProvider'
Expand All @@ -14,11 +8,6 @@ import {
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'
import {
ensureSuspenseTimers,
getSuspensePromise,
shouldSuspend,
} from './suspense'
import { useSyncExternalStore } from './utils'
import type {
DefaultError,
Expand All @@ -31,6 +20,7 @@ import type {
QueryObserverOptions,
ThrowOnError,
} from '@tanstack/query-core'
import type { suspenseQueriesPolicy } from './suspense'
import type {
DefinedUseQueryResult,
UseQueryOptions,
Expand Down Expand Up @@ -224,6 +214,28 @@ export type QueriesResults<
>
: { [K in keyof T]: GetUseQueryResult<T[K]> }

type UseQueriesInput<T extends Array<any>, TCombinedResult> = {
/**
* An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and
* `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
* `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
* and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
*/
queries:
| readonly [...QueriesOptions<T>]
| readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
/**
* Use this to combine the results of the queries into a single value. The result will be structurally
* shared to be as referentially stable as possible.
*/
combine?: (result: QueriesResults<T>) => TCombinedResult
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
* @defaultValue true
*/
subscribed?: boolean
}

/**
* The `useQueries` hook can be used to fetch a variable number of queries.
*
Expand Down Expand Up @@ -305,31 +317,28 @@ export function useQueries<
T extends Array<any>,
TCombinedResult = QueriesResults<T>,
>(
{
queries,
...options
}: {
/**
* An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and
* `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
* `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
* and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
*/
queries:
| readonly [...QueriesOptions<T>]
| readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
/**
* Use this to combine the results of the queries into a single value. The result will be structurally
* shared to be as referentially stable as possible.
*/
combine?: (result: QueriesResults<T>) => TCombinedResult
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
* @defaultValue true
*/
subscribed?: boolean
},
options: UseQueriesInput<T, TCombinedResult>,
queryClient?: QueryClient,
): TCombinedResult {
return useBaseQueries(options, queryClient)
}

/**
* Reads and subscribes to multiple queries. The dedicated Suspense hook can
* supply a render-time policy.
* @param options - The queries, combiner, and subscription setting.
* @param queryClient - The client to use in place of the nearest provider.
* @param suspense - The policy that prepares and reads queries during render.
* @returns The individual query results or the combined result.
* @throws {Error} The first query error configured to reach the error boundary.
*/
export function useBaseQueries<
T extends Array<any>,
TCombinedResult = QueriesResults<T>,
>(
{ queries, ...options }: UseQueriesInput<T, TCombinedResult>,
queryClient?: QueryClient,
suspense?: typeof suspenseQueriesPolicy,
): TCombinedResult {
const client = useQueryClient(queryClient)
const isRestoring = useIsRestoring()
Expand All @@ -339,9 +348,10 @@ export function useQueries<
const defaultedQueries = useMemo(
() =>
queries.map((opts) => {
const defaultedOptions = client.defaultQueryOptions(
opts as QueryObserverOptions,
)
const defaultedOptions = client.defaultQueryOptions({
...opts,
suspense: !!suspense,
} as QueryObserverOptions)

// Make sure the results are already in fetching state before subscribing or updating options
defaultedOptions._optimisticResults = isRestoring
Expand All @@ -352,11 +362,11 @@ export function useQueries<

return defaultedOptions
}),
[queries, client, isRestoring, subscribed],
[queries, client, isRestoring, subscribed, suspense],
)

defaultedQueries.forEach((queryOptions) => {
ensureSuspenseTimers(queryOptions)
suspense?.prepare(queryOptions)
const query = client.getQueryCache().get(queryOptions.queryHash)
ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
})
Expand All @@ -376,33 +386,8 @@ export function useQueries<
defaultedQueries,
options as QueriesObserverOptions<TCombinedResult>,
)
const snapshot = reader.getSnapshot()

const shouldAtLeastOneSuspend = snapshot.some((result, index) =>
shouldSuspend(defaultedQueries[index], result),
)

const suspensePromises = shouldAtLeastOneSuspend
? snapshot.flatMap((result, index) => {
const opts = defaultedQueries[index]
suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary)

if (opts && shouldSuspend(opts, result)) {
const queryObserver = new QueryObserver(client, opts)
return getSuspensePromise(
opts,
queryObserver,
errorResetBoundary,
queryObserver.getCurrentQuery(),
)
}
return []
})
: []

if (suspensePromises.length > 0) {
// Keep the boundary suspended until every pending query has settled.
use(Promise.all(suspensePromises))
}
// Commit the combine cache before subscription can start a fetch.
useEffect(() => {
reader.commit()
Expand Down
4 changes: 2 additions & 2 deletions packages/preact-query/src/useSuspenseInfiniteQuery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
import { defaultThrowOnError } from './suspense'
import { defaultThrowOnError, suspenseQueryPolicy } from './suspense'
import { useBaseQuery } from './useBaseQuery'
import type {
DefaultError,
Expand Down Expand Up @@ -144,11 +144,11 @@ export function useSuspenseInfiniteQuery<
{
...options,
enabled: true,
suspense: true,
throwOnError: defaultThrowOnError,
placeholderData: undefined,
},
InfiniteQueryObserver as typeof QueryObserver,
queryClient,
suspenseQueryPolicy,
) as InfiniteQueryObserverSuccessResult<TData, TError>
}
Loading
Loading