Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

hydration.ts

161 lines4.1 KB

1import type { QueryClient } from './queryClient'
2import type { Query, QueryState } from './query'
3import type {
4 MutationKey,
5 MutationMeta,
6 MutationOptions,
7 QueryKey,
8 QueryMeta,
9 QueryOptions,
10} from './types'
11import type { Mutation, MutationState } from './mutation'
12​
13// TYPES
14​
15export interface DehydrateOptions {
16 shouldDehydrateMutation?: (mutation: Mutation) => boolean
17 shouldDehydrateQuery?: (query: Query) => boolean
19​
20export interface HydrateOptions {
21 defaultOptions?: {
22 queries?: QueryOptions
23 mutations?: MutationOptions
24 }
26​
27interface DehydratedMutation {
28 mutationKey?: MutationKey
29 state: MutationState
30 meta?: MutationMeta
32​
33interface DehydratedQuery {
34 queryHash: string
35 queryKey: QueryKey
36 state: QueryState
37 meta?: QueryMeta
39​
40export interface DehydratedState {
41 mutations: Array<DehydratedMutation>
42 queries: Array<DehydratedQuery>
44​
45// FUNCTIONS
46​
47function dehydrateMutation(mutation: Mutation): DehydratedMutation {
48 return {
49 mutationKey: mutation.options.mutationKey,
50 state: mutation.state,
51 ...(mutation.meta && { meta: mutation.meta }),
52 }
54​
55// Most config is not dehydrated but instead meant to configure again when
56// consuming the de/rehydrated data, typically with useQuery on the client.
57// Sometimes it might make sense to prefetch data on the server and include
58// in the html-payload, but not consume it on the initial render.
59function dehydrateQuery(query: Query): DehydratedQuery {
60 return {
61 state: query.state,
62 queryKey: query.queryKey,
63 queryHash: query.queryHash,
64 ...(query.meta && { meta: query.meta }),
65 }
67​
68export function defaultShouldDehydrateMutation(mutation: Mutation) {
69 return mutation.state.isPaused
71​
72export function defaultShouldDehydrateQuery(query: Query) {
73 return query.state.status === 'success'
75​
76export function dehydrate(
77 client: QueryClient,
78 options: DehydrateOptions = {},
79): DehydratedState {
80 const filterMutation =
81 options.shouldDehydrateMutation ?? defaultShouldDehydrateMutation
82​
83 const mutations = client
84 .getMutationCache()
85 .getAll()
86 .flatMap((mutation) =>
87 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
88 )
89​
90 const filterQuery =
91 options.shouldDehydrateQuery ?? defaultShouldDehydrateQuery
92​
93 const queries = client
94 .getQueryCache()
95 .getAll()
96 .flatMap((query) => (filterQuery(query) ? [dehydrateQuery(query)] : []))
97​
98 return { mutations, queries }
100​
101export function hydrate(
102 client: QueryClient,
103 dehydratedState: unknown,
104 options?: HydrateOptions,
105): void {
106 if (typeof dehydratedState !== 'object' || dehydratedState === null) {
107 return
108 }
109​
110 const mutationCache = client.getMutationCache()
111 const queryCache = client.getQueryCache()
112​
113 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
114 const mutations = (dehydratedState as DehydratedState).mutations || []
115 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
116 const queries = (dehydratedState as DehydratedState).queries || []
117​
118 mutations.forEach((dehydratedMutation) => {
119 mutationCache.build(
120 client,
121 {
122 ...options?.defaultOptions?.mutations,
123 mutationKey: dehydratedMutation.mutationKey,
124 meta: dehydratedMutation.meta,
125 },
126 dehydratedMutation.state,
127 )
128 })
129​
130 queries.forEach(({ queryKey, state, queryHash, meta }) => {
131 const query = queryCache.get(queryHash)
132​
133 // Do not hydrate if an existing query exists with newer data
134 if (query) {
135 if (query.state.dataUpdatedAt < state.dataUpdatedAt) {
136 // omit fetchStatus from dehydrated state
137 // so that query stays in its current fetchStatus
138 const { fetchStatus: _ignored, ...dehydratedQueryState } = state
139 query.setState(dehydratedQueryState)
140 }
141 return
142 }
143​
144 // Restore query
145 queryCache.build(
146 client,
147 {
148 ...options?.defaultOptions?.queries,
149 queryKey,
150 queryHash,
151 meta,
152 },
153 // Reset fetch status to idle to avoid
154 // query being stuck in fetching state upon hydration
155 {
156 ...state,
157 fetchStatus: 'idle',
158 },
159 )
160 })