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 */
28export async function dehydrateSettled(
29 client: QueryClient,
30 options?: DehydrateOptions,
31): Promise<DehydratedState> {
32 const cache = client.getQueryCache()
33 for (;;) {
34 const pending = cache
35 .getAll()
36 .filter((query) => query.state.fetchStatus !== 'idle')
37 .map((query) => query.promise)
38 if (pending.length === 0) break
39 await Promise.allSettled(pending)
40 }
41 return dehydrate(client, options)
42}