Open History to see the last commit
1import { dehydrate } from '@tanstack/query-core'
2import type { DehydrateOptions, DehydratedState } from '@tanstack/query-core'
3import type { QueryClient } from './QueryClient'
4β
5/**
6 * Waits for every fetch the client has in flight to settle, then
7 * dehydrates. This is the extraction half of a single-flight collector:
8 * after route data functions run for the mutation's target URL, loaders
9 * commonly kick off prefetches without awaiting them β plain
10 * `dehydrate()` would snapshot those mid-fetch and ship nothing.
11 *
12 * ```ts
13 * registerFlightDataSource(FLIGHT_DATA_SOURCE, (event, outcome) =>
14 * loadFlightTarget({
15 * router,
16 * event,
17 * outcome,
18 * collect: () => dehydrateSettled(queryClient),
19 * }),
20 * )
21 * ```
22 *
23 * Settling is chased to quiescence β awaiting one batch of fetches can
24 * dispatch more (dependent queries keyed off a first result) β so an
25 * unconditionally self-refetching query would keep this pending; that's
26 * an app bug mirrored, not guarded.
27 * @param client - The `QueryClient` whose cache is dehydrated.
28 * @param options - The `DehydrateOptions` forwarded to `dehydrate`.
29 * @returns A promise for the dehydrated state, taken once no fetch is in flight.
30 */
31export async function dehydrateSettled(
32 client: QueryClient,
33 options?: DehydrateOptions,
34): Promise<DehydratedState> {
35 const cache = client.getQueryCache()
36 for (;;) {
37 const pending = cache
38 .getAll()
39 .filter((query) => query.state.fetchStatus !== 'idle')
40 .map((query) => query.promise)
41 if (pending.length === 0) break
42 await Promise.allSettled(pending)
43 }
44 return dehydrate(client, options)
45}