MCPcopy Create free account
hub / github.com/TanStack/query / dehydrateQuery

Function dehydrateQuery

packages/query-core/src/hydration.ts:78–123  ·  view source on GitHub ↗
(
  query: Query,
  serializeData: TransformerFn,
  shouldRedactErrors: (error: unknown) => boolean,
)

Source from the content-addressed store, hash-verified

76// Sometimes it might make sense to prefetch data on the server and include
77// in the html-payload, but not consume it on the initial render.
78function dehydrateQuery(
79 query: Query,
80 serializeData: TransformerFn,
81 shouldRedactErrors: (error: unknown) => boolean,
82): DehydratedQuery {
83 const dehydratePromise = () => {
84 const promise = query.promise?.then(serializeData).catch((error) => {
85 if (!shouldRedactErrors(error)) {
86 // Reject original error if it should not be redacted
87 return Promise.reject(error)
88 }
89 // If not in production, log original error before rejecting redacted error
90 if (process.env.NODE_ENV !== 'production') {
91 console.error(
92 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
93 )
94 }
95 return Promise.reject(new Error('redacted'))
96 })
97
98 // Avoid unhandled promise rejections
99 // We need the promise we dehydrate to reject to get the correct result into
100 // the query cache, but we also want to avoid unhandled promise rejections
101 // in whatever environment the prefetches are happening in.
102 promise?.catch(noop)
103
104 return promise
105 }
106
107 return {
108 dehydratedAt: Date.now(),
109 state: {
110 ...query.state,
111 ...(query.state.data !== undefined && {
112 data: serializeData(query.state.data),
113 }),
114 },
115 queryKey: query.queryKey,
116 queryHash: query.queryHash,
117 ...(query.state.status === 'pending' && {
118 promise: dehydratePromise(),
119 }),
120 ...(query.meta && { meta: query.meta }),
121 ...(query.queryType && { queryType: query.queryType }),
122 }
123}
124
125export function defaultShouldDehydrateMutation(mutation: Mutation) {
126 return mutation.state.isPaused

Callers 1

dehydrateFunction · 0.85

Calls 1

dehydratePromiseFunction · 0.85

Tested by

no test coverage detected