Open History to see the last commit
1import { noop } from './utils'
2import type { Mutation, MutationState } from './mutation'
3import type { Query, QueryState } from './query'
4import type { QueryClient } from './queryClient'
5import type {
6 DefaultError,
7 MutationKey,
8 MutationMeta,
9 MutationOptions,
10 MutationScope,
11 QueryKey,
12 QueryMeta,
13 QueryOptions,
14} from './types'
15β
16// TYPES
17type TransformerFn = (data: any) => any
18β
19/**
20 * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that
21 * resolves within its `then` call.
22 * @param promise - The promise to read.
23 * @returns An object with the resolved `data`, or `undefined` if the promise hasn't resolved
24 * synchronously (or resolved with `undefined`).
25 */
26function tryResolveSync(promise: PromiseLike<unknown>) {
27 let data: unknown
28β
29 const thenResult = promise.then((result) => {
30 data = result
31 return result
32 }, noop) as Promise<unknown> | undefined
33β
34 // .catch can be unavailable on certain kinds of thenable's
35 // oxlint-disable-next-line typescript/no-unnecessary-condition
36 thenResult?.catch?.(noop)
37β
38 if (data !== undefined) {
39 return { data }
40 }
41β
42 return undefined
43}
44β
45/**
46 * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and
47 * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).
48 */
49export interface DehydrateOptions {
50 /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */
51 serializeData?: TransformerFn
52 /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */
53 shouldDehydrateMutation?: (mutation: Mutation) => boolean
54 /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */
55 shouldDehydrateQuery?: (query: Query) => boolean
56 /**
57 * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted
58 * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the
59 * given error, in which case the original error is kept.
60 */
61 shouldRedactErrors?: (error: unknown) => boolean
62}
63β
64/**
65 * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a
66 * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.
67 */
68export interface HydrateOptions {
69 /** Options applied to the queries and mutations restored from the dehydrated state. */
70 defaultOptions?: {
71 /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */
72 deserializeData?: TransformerFn
73 /** Default options merged into every query restored from the dehydrated state. */
74 queries?: QueryOptions
75 /** Default options merged into every mutation restored from the dehydrated state. */
76 mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>
77 }
78}
79β
80interface DehydratedMutation {
81 mutationKey?: MutationKey
82 state: MutationState
83 meta?: MutationMeta
84 scope?: MutationScope
85}
86β
87interface DehydratedQuery {
88 queryHash: string
89 queryKey: QueryKey
90 state: QueryState
91 dehydratedAt: number
92 promise?: Promise<unknown>
93 meta?: QueryMeta
94 queryType?: 'infinite'
95}
96β
97/**
98 * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically
99 * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data
100 * that has already been fetched, avoiding a redundant fetch on the client.
101 */
102export interface DehydratedState {
103 /**
104 * The dehydrated mutations, by default only the paused ones.
105 */
106 mutations: Array<DehydratedMutation>
107 /**
108 * The dehydrated queries, by default only the successful ones.
109 */
110 queries: Array<DehydratedQuery>
111}
112β
113// FUNCTIONS
114β
115/**
116 * Dehydrates a single `Mutation` into a serializable snapshot of its key, state, scope, and meta.
117 * @param mutation - The mutation to dehydrate.
118 * @returns The dehydrated mutation.
119 */
120function dehydrateMutation(mutation: Mutation): DehydratedMutation {
121 return {
122 mutationKey: mutation.options.mutationKey,
123 state: mutation.state,
124 ...(mutation.options.scope && { scope: mutation.options.scope }),
125 ...(mutation.meta && { meta: mutation.meta }),
126 }
127}
128β
129/**
130 * Prepares the in-flight promise of a pending query for dehydration: applies `serializeData` to its
131 * result, and redacts its rejection error unless `shouldRedactErrors` returns `false` for it.
132 * @param query - The pending query whose promise is dehydrated.
133 * @param serializeData - Optional transform applied to the resolved data.
134 * @param shouldRedactErrors - Optional predicate; if it returns `false` for the rejection error,
135 * that
136 * error is kept as-is instead of being redacted.
137 * @returns The transformed promise, or `undefined` if the query has no in-flight promise.
138 */
139function dehydratePromise(
140 query: Query,
141 serializeData?: TransformerFn,
142 shouldRedactErrors?: (error: unknown) => boolean,
143): Promise<unknown> | undefined {
144 const promise = query.promise?.then(serializeData).catch((error) => {
145 if (shouldRedactErrors?.(error) === false) {
146 // Reject original error if it should not be redacted
147 return Promise.reject(error)
148 }
149 // If not in production, log original error before rejecting redacted error
150 if (process.env.NODE_ENV !== 'production') {
151 console.error(
152 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
153 )
154 }
155 return Promise.reject(new Error('redacted'))
156 })
157β
158 // Avoid unhandled promise rejections
159 // We need the promise we dehydrate to reject to get the correct result into
160 // the query cache, but we also want to avoid unhandled promise rejections
161 // in whatever environment the prefetches are happening in.
162 promise?.catch(noop)
163β
164 return promise
165}
166β
167/**
168 * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
169 * `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
170 * de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
171 * promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
172 * @param query - The query to dehydrate.
173 * @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
174 * @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
175 * error is kept as-is instead of being redacted.
176 * @returns The dehydrated query.
177 */
178export function dehydrateQuery(
179 query: Query,
180 serializeData?: TransformerFn,
181 shouldRedactErrors?: (error: unknown) => boolean,
182): DehydratedQuery {
183 return {
184 dehydratedAt: Date.now(),
185 state: {
186 ...query.state,
187 ...(query.state.data !== undefined && {
188 data: serializeData
189 ? serializeData(query.state.data)
190 : query.state.data,
191 }),
192 },
193 queryKey: query.queryKey,
194 queryHash: query.queryHash,
195 ...(query.state.status === 'pending' && {
196 promise: dehydratePromise(query, serializeData, shouldRedactErrors),
197 }),
198 ...(query.meta && { meta: query.meta }),
199 ...(query.queryType && { queryType: query.queryType }),
200 }
201}
202β
203/**
204 * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
205 * currently paused (e.g. paused by `networkMode` while offline).
206 * @param mutation - The mutation to check.
207 * @returns `true` if the mutation is paused.
208 */
209export function defaultShouldDehydrateMutation(mutation: Mutation) {
210 return mutation.state.isPaused
211}
212β
213/**
214 * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
215 * `'success'`.
216 * @param query - The query to check.
217 * @returns `true` if the query's status is `'success'`.
218 */
219export function defaultShouldDehydrateQuery(query: Query) {
220 return query.state.status === 'success'
221}
222β
223/**
224 * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
225 * typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
226 * Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
227 * falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
228 * `defaultShouldDehydrateMutation`.
229 * @param client - The client whose cache is dehydrated.
230 * @param options - Controls which queries and mutations are included and how their data and errors
231 * are transformed. Each option falls back to the client's `defaultOptions.dehydrate`.
232 * @returns The dehydrated state, with the included `queries` and `mutations`.
233 * @example
234 * ```ts
235 * const queryClient = new QueryClient()
236 *
237 * await queryClient.prefetchQuery({
238 * queryKey: ['posts'],
239 * queryFn: getPosts,
240 * })
241 *
242 * const dehydratedState = dehydrate(queryClient)
243 * ```
244 */
245export function dehydrate(
246 client: QueryClient,
247 options: DehydrateOptions = {},
248): DehydratedState {
249 const filterMutation =
250 options.shouldDehydrateMutation ??
251 client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ??
252 defaultShouldDehydrateMutation
253β
254 const mutations = client
255 .getMutationCache()
256 .getAll()
257 .flatMap((mutation) =>
258 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
259 )
260β
261 const filterQuery =
262 options.shouldDehydrateQuery ??
263 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ??
264 defaultShouldDehydrateQuery
265β
266 const shouldRedactErrors =
267 options.shouldRedactErrors ??
268 client.getDefaultOptions().dehydrate?.shouldRedactErrors
269β
270 const serializeData =
271 options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData
272β
273 const queries = client
274 .getQueryCache()
275 .getAll()
276 .flatMap((query) =>
277 filterQuery(query)
278 ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
279 : [],
280 )
281β
282 return { mutations, queries }
283}
284β
285/**
286 * Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
287 * client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
288 * Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
289 * when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
290 * to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
291 * promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
292 * `queryFn`.
293 * @param client - The client whose cache is restored into.
294 * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate` on the server.
295 * @param options - `defaultOptions` merged into every restored query and mutation (on top of the
296 * client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`.
297 * @example
298 * ```ts
299 * // dehydratedState was produced by `dehydrate` on the server
300 * // and sent to the client, e.g. embedded in server-rendered markup.
301 * const queryClient = new QueryClient()
302 *
303 * hydrate(queryClient, dehydratedState)
304 * ```
305 */
306export function hydrate(
307 client: QueryClient,
308 dehydratedState: Partial<DehydratedState>,
309 options?: HydrateOptions,
310): void {
311 const mutationCache = client.getMutationCache()
312 const queryCache = client.getQueryCache()
313 const deserializeData =
314 options?.defaultOptions?.deserializeData ??
315 client.getDefaultOptions().hydrate?.deserializeData
316β
317 dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => {
318 mutationCache.build(
319 client,
320 {
321 ...client.getDefaultOptions().hydrate?.mutations,
322 ...options?.defaultOptions?.mutations,
323 ...mutationOptions,
324 },
325 state,
326 )
327 })
328β
329 dehydratedState.queries?.forEach(
330 ({
331 queryKey,
332 state,
333 queryHash,
334 meta,
335 promise,
336 dehydratedAt,
337 queryType,
338 }) => {
339 const syncData = promise ? tryResolveSync(promise) : undefined
340 const rawData = state.data === undefined ? syncData?.data : state.data
341 const data =
342 rawData === undefined
343 ? rawData
344 : deserializeData
345 ? deserializeData(rawData)
346 : rawData
347β
348 let query = queryCache.get(queryHash)
349 const existingQueryIsPending = query?.state.status === 'pending'
350 const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
351β
352 // Do not hydrate if an existing query exists with newer data
353 if (query) {
354 const hasNewerSyncData =
355 syncData && dehydratedAt > query.state.dataUpdatedAt
356 if (
357 state.dataUpdatedAt > query.state.dataUpdatedAt ||
358 hasNewerSyncData
359 ) {
360 // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus
361 const { fetchStatus: _ignored, ...serializedState } = state
362 query.setState({
363 ...serializedState,
364 data,
365 // If the query was pending at the moment of dehydration, but resolved to have data
366 // before hydration, we can assume the query should be hydrated as successful.
367 //
368 // Since you can opt into dehydrating failed queries, and those can have data from
369 // previous successful fetches, we make sure we only do this for pending queries.
370 ...(state.status === 'pending' &&
371 data !== undefined && {
372 status: 'success' as const,
373 dataUpdatedAt: dehydratedAt,
374 // Preserve existing fetchStatus if the existing query is actively fetching.
375 ...(!existingQueryIsFetching && {
376 fetchStatus: 'idle' as const,
377 }),
378 }),
379 })
380 }
381 } else {
382 // Restore query
383 query = queryCache.build(
384 client,
385 {
386 ...client.getDefaultOptions().hydrate?.queries,
387 ...options?.defaultOptions?.queries,
388 queryKey,
389 queryHash,
390 meta,
391 _type: queryType,
392 },
393 // Reset fetch status to idle to avoid
394 // query being stuck in fetching state upon hydration
395 {
396 ...state,
397 data,
398 fetchStatus: 'idle',
399 // Like above, if the query was pending at the moment of dehydration but has data,
400 // we can assume it should be hydrated as successful.
401 status:
402 state.status === 'pending' && data !== undefined
403 ? 'success'
404 : state.status,
405 ...(state.status === 'pending' &&
406 data !== undefined && {
407 dataUpdatedAt: dehydratedAt,
408 }),
409 },
410 )
411 }
412β
413 if (
414 promise &&
415 // If the data was synchronously available, there is no need to set up
416 // a retryer and thus no reason to call fetch
417 !syncData &&
418 !existingQueryIsPending &&
419 !existingQueryIsFetching &&
420 // Only hydrate if dehydration is newer than any existing data,
421 // this is always true for new queries
422 dehydratedAt > query.state.dataUpdatedAt
423 ) {
424 // This doesn't actually fetch - it just creates a retryer
425 // which will re-use the passed `initialPromise`
426 query
427 .fetch(undefined, {
428 // RSC transformed promises are not thenable
429 initialPromise: Promise.resolve(promise).then(deserializeData),
430 })
431 // Avoid unhandled promise rejections
432 .catch(noop)
433 }
434 },
435 )
436}