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