Open History to see the last commit
1import * as coreModule from '@tanstack/query-core'
2import { createKey, sleep } from '@tanstack/query-test-utils'
3import { render } from '@testing-library/preact'
4import { Suspense, startTransition } from 'preact/compat'
5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6β
7import {
8 HydrationBoundary,
9 QueryClient,
10 QueryClientProvider,
11 dehydrate,
12 noop,
13 useQuery,
14} from '..'
15import type { hydrate } from '@tanstack/query-core'
16β
17describe('Preact hydration', () => {
18 const stringKey = createKey()
19 const addedKey = createKey()
20 const promiseKey = createKey()
21 let stringifiedState: string
22β
23 beforeEach(async () => {
24 vi.useFakeTimers()
25 const queryClient = new QueryClient()
26 void queryClient
27 .query({
28 queryKey: stringKey,
29 queryFn: () => sleep(10).then(() => ['stringCached']),
30 })
31 .catch(noop)
32 await vi.advanceTimersByTimeAsync(10)
33 const dehydrated = dehydrate(queryClient)
34 stringifiedState = JSON.stringify(dehydrated)
35 queryClient.clear()
36 })
37β
38 afterEach(() => {
39 vi.useRealTimers()
40 })
41β
42 it('should hydrate queries to the cache on context', async () => {
43 const dehydratedState = JSON.parse(stringifiedState)
44 const queryClient = new QueryClient()
45β
46 function Page() {
47 const { data } = useQuery({
48 queryKey: stringKey,
49 queryFn: () => sleep(20).then(() => ['string']),
50 })
51 return (
52 <div>
53 <h1>{data}</h1>
54 </div>
55 )
56 }
57β
58 const rendered = render(
59 <QueryClientProvider client={queryClient}>
60 <HydrationBoundary state={dehydratedState}>
61 <Page />
62 </HydrationBoundary>
63 </QueryClientProvider>,
64 )
65β
66 expect(rendered.getByText('stringCached')).toBeInTheDocument()
67 await vi.advanceTimersByTimeAsync(21)
68 expect(rendered.getByText('string')).toBeInTheDocument()
69 queryClient.clear()
70 })
71β
72 it('should hydrate queries to the cache on custom context', async () => {
73 const queryClientInner = new QueryClient()
74 const queryClientOuter = new QueryClient()
75β
76 const dehydratedState = JSON.parse(stringifiedState)
77β
78 function Page() {
79 const { data } = useQuery({
80 queryKey: stringKey,
81 queryFn: () => sleep(20).then(() => ['string']),
82 })
83 return (
84 <div>
85 <h1>{data}</h1>
86 </div>
87 )
88 }
89β
90 const rendered = render(
91 <QueryClientProvider client={queryClientOuter}>
92 <QueryClientProvider client={queryClientInner}>
93 <HydrationBoundary state={dehydratedState}>
94 <Page />
95 </HydrationBoundary>
96 </QueryClientProvider>
97 </QueryClientProvider>,
98 )
99β
100 expect(rendered.getByText('stringCached')).toBeInTheDocument()
101 await vi.advanceTimersByTimeAsync(21)
102 expect(rendered.getByText('string')).toBeInTheDocument()
103β
104 queryClientInner.clear()
105 queryClientOuter.clear()
106 })
107β
108 describe('PreactQueryCacheProvider with hydration support', () => {
109 it('should hydrate new queries if queries change', async () => {
110 const dehydratedState = JSON.parse(stringifiedState)
111 const queryClient = new QueryClient()
112β
113 function Page({ queryKey: pageKey }: { queryKey: Array<string> }) {
114 const { data } = useQuery({
115 queryKey: pageKey,
116 queryFn: () => sleep(20).then(() => pageKey),
117 })
118 return (
119 <div>
120 <h1>{data}</h1>
121 </div>
122 )
123 }
124β
125 const rendered = render(
126 <QueryClientProvider client={queryClient}>
127 <HydrationBoundary state={dehydratedState}>
128 <Page queryKey={stringKey} />
129 </HydrationBoundary>
130 </QueryClientProvider>,
131 )
132β
133 expect(rendered.getByText('stringCached')).toBeInTheDocument()
134 await vi.advanceTimersByTimeAsync(21)
135 expect(rendered.getByText(stringKey[0]!)).toBeInTheDocument()
136β
137 const intermediateClient = new QueryClient()
138β
139 void intermediateClient
140 .query({
141 queryKey: stringKey,
142 queryFn: () => sleep(20).then(() => ['should change']),
143 })
144 .catch(noop)
145 void intermediateClient
146 .query({
147 queryKey: addedKey,
148 queryFn: () => sleep(20).then(() => [addedKey[0]]),
149 })
150 .catch(noop)
151 await vi.advanceTimersByTimeAsync(20)
152 const dehydrated = dehydrate(intermediateClient)
153 intermediateClient.clear()
154β
155 rendered.rerender(
156 <QueryClientProvider client={queryClient}>
157 <HydrationBoundary state={dehydrated}>
158 <Page queryKey={stringKey} />
159 <Page queryKey={addedKey} />
160 </HydrationBoundary>
161 </QueryClientProvider>,
162 )
163β
164 // Existing observer should not have updated at this point,
165 // as that would indicate a side effect in the render phase
166 expect(rendered.getByText(stringKey[0]!)).toBeInTheDocument()
167 // New query data should be available immediately
168 expect(rendered.getByText(addedKey[0]!)).toBeInTheDocument()
169 await vi.advanceTimersByTimeAsync(0)
170 // After effects phase has had time to run, the observer should have updated
171 expect(rendered.queryByText(stringKey[0]!)).not.toBeInTheDocument()
172 expect(rendered.getByText('should change')).toBeInTheDocument()
173β
174 queryClient.clear()
175 })
176β
177 // When we hydrate in transitions that are later aborted, it could be
178 // confusing to both developers and users if we suddenly updated existing
179 // state on the screen (why did this update when it was not stale, nothing
180 // remounted, I didn't change tabs etc?).
181 // Any queries that does not exist in the cache yet can still be hydrated
182 // since they don't have any observers on the current page that would update.
183 it('should hydrate new but not existing queries if transition is aborted', async () => {
184 const initialDehydratedState = JSON.parse(stringifiedState)
185 const queryClient = new QueryClient()
186β
187 function Page({ queryKey: pageKey }: { queryKey: Array<string> }) {
188 const { data } = useQuery({
189 queryKey: pageKey,
190 queryFn: () => sleep(20).then(() => pageKey),
191 })
192 return (
193 <div>
194 <h1>{data}</h1>
195 </div>
196 )
197 }
198β
199 const rendered = render(
200 <QueryClientProvider client={queryClient}>
201 <HydrationBoundary state={initialDehydratedState}>
202 <Page queryKey={stringKey} />
203 </HydrationBoundary>
204 </QueryClientProvider>,
205 )
206β
207 expect(rendered.getByText('stringCached')).toBeInTheDocument()
208 await vi.advanceTimersByTimeAsync(21)
209 expect(rendered.getByText(stringKey[0]!)).toBeInTheDocument()
210β
211 const intermediateClient = new QueryClient()
212 void intermediateClient
213 .query({
214 queryKey: stringKey,
215 queryFn: () => sleep(20).then(() => ['should not change']),
216 })
217 .catch(noop)
218 void intermediateClient
219 .query({
220 queryKey: addedKey,
221 queryFn: () => sleep(20).then(() => [addedKey[0]]),
222 })
223 .catch(noop)
224 await vi.advanceTimersByTimeAsync(20)
225β
226 const newDehydratedState = dehydrate(intermediateClient)
227 intermediateClient.clear()
228β
229 function Thrower(): never {
230 throw new Promise(() => {
231 // Never resolve
232 })
233 }
234β
235 startTransition(() => {
236 rendered.rerender(
237 <Suspense fallback="loading">
238 <QueryClientProvider client={queryClient}>
239 <HydrationBoundary state={newDehydratedState}>
240 <Page queryKey={stringKey} />
241 <Page queryKey={addedKey} />
242 <Thrower />
243 </HydrationBoundary>
244 </QueryClientProvider>
245 </Suspense>,
246 )
247β
248 expect(rendered.getByText('loading')).toBeInTheDocument()
249 })
250β
251 startTransition(() => {
252 rendered.rerender(
253 <QueryClientProvider client={queryClient}>
254 <HydrationBoundary state={initialDehydratedState}>
255 <Page queryKey={stringKey} />
256 <Page queryKey={addedKey} />
257 </HydrationBoundary>
258 </QueryClientProvider>,
259 )
260β
261 // This query existed before the transition so it should stay the same
262 expect(rendered.getByText(stringKey[0]!)).toBeInTheDocument()
263 expect(
264 rendered.queryByText('should not change'),
265 ).not.toBeInTheDocument()
266 // New query data should be available immediately because it was
267 // hydrated in the previous transition, even though the new dehydrated
268 // state did not contain it
269 expect(rendered.getByText(addedKey[0]!)).toBeInTheDocument()
270 })
271β
272 await vi.advanceTimersByTimeAsync(20)
273 // It should stay the same even after effects have had a chance to run
274 expect(rendered.getByText(stringKey[0]!)).toBeInTheDocument()
275 expect(rendered.queryByText('should not change')).not.toBeInTheDocument()
276β
277 queryClient.clear()
278 })
279β
280 it('should hydrate queries to new cache if cache changes', async () => {
281 const dehydratedState = JSON.parse(stringifiedState)
282 const queryClient = new QueryClient()
283β
284 function Page() {
285 const { data } = useQuery({
286 queryKey: stringKey,
287 queryFn: () => sleep(20).then(() => ['string']),
288 })
289 return (
290 <div>
291 <h1>{data}</h1>
292 </div>
293 )
294 }
295β
296 const rendered = render(
297 <QueryClientProvider client={queryClient}>
298 <HydrationBoundary state={dehydratedState}>
299 <Page />
300 </HydrationBoundary>
301 </QueryClientProvider>,
302 )
303β
304 expect(rendered.getByText('stringCached')).toBeInTheDocument()
305 await vi.advanceTimersByTimeAsync(21)
306 expect(rendered.getByText('string')).toBeInTheDocument()
307 const newClientQueryClient = new QueryClient()
308β
309 rendered.rerender(
310 <QueryClientProvider client={newClientQueryClient}>
311 <HydrationBoundary state={dehydratedState}>
312 <Page />
313 </HydrationBoundary>
314 </QueryClientProvider>,
315 )
316β
317 await vi.advanceTimersByTimeAsync(20)
318 expect(rendered.getByText('string')).toBeInTheDocument()
319β
320 queryClient.clear()
321 newClientQueryClient.clear()
322 })
323 })
324β
325 it('should not hydrate queries if state is null', async () => {
326 const queryClient = new QueryClient()
327β
328 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
329β
330 function Page() {
331 return null
332 }
333β
334 render(
335 <QueryClientProvider client={queryClient}>
336 <HydrationBoundary state={null}>
337 <Page />
338 </HydrationBoundary>
339 </QueryClientProvider>,
340 )
341β
342 await Promise.all(
343 Array.from({ length: 1000 }).map(async (_, index) => {
344 await vi.advanceTimersByTimeAsync(index)
345 expect(hydrateSpy).toHaveBeenCalledTimes(0)
346 }),
347 )
348β
349 queryClient.clear()
350 })
351β
352 it('should not hydrate queries if state is undefined', async () => {
353 const queryClient = new QueryClient()
354β
355 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
356β
357 function Page() {
358 return null
359 }
360β
361 render(
362 <QueryClientProvider client={queryClient}>
363 <HydrationBoundary state={undefined}>
364 <Page />
365 </HydrationBoundary>
366 </QueryClientProvider>,
367 )
368β
369 await vi.advanceTimersByTimeAsync(0)
370 expect(hydrateSpy).toHaveBeenCalledTimes(0)
371β
372 queryClient.clear()
373 })
374β
375 it('should not hydrate queries if state is not an object', async () => {
376 const queryClient = new QueryClient()
377β
378 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
379β
380 function Page() {
381 return null
382 }
383β
384 render(
385 <QueryClientProvider client={queryClient}>
386 <HydrationBoundary state={'invalid-state' as any}>
387 <Page />
388 </HydrationBoundary>
389 </QueryClientProvider>,
390 )
391β
392 await vi.advanceTimersByTimeAsync(0)
393 expect(hydrateSpy).toHaveBeenCalledTimes(0)
394β
395 queryClient.clear()
396 })
397β
398 it('should handle state without queries property gracefully', async () => {
399 const queryClient = new QueryClient()
400β
401 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
402β
403 function Page() {
404 return null
405 }
406β
407 render(
408 <QueryClientProvider client={queryClient}>
409 <HydrationBoundary state={{} as any}>
410 <Page />
411 </HydrationBoundary>
412 </QueryClientProvider>,
413 )
414β
415 await vi.advanceTimersByTimeAsync(0)
416 expect(hydrateSpy).toHaveBeenCalledTimes(0)
417β
418 queryClient.clear()
419 })
420β
421 // https://github.com/TanStack/query/issues/8677
422 it('should not infinite loop when hydrating promises that resolve to errors', async () => {
423 const originalHydrate = coreModule.hydrate
424 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
425 let hydrationCount = 0
426 hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
427 hydrationCount++
428 // Arbitrary number
429 if (hydrationCount > 10) {
430 // This is a rough way to detect it. Calling hydrate multiple times with
431 // the same data is usually fine, but in this case it indicates the
432 // logic in HydrationBoundary is not working as expected.
433 throw new Error('Too many hydrations detected')
434 }
435 return originalHydrate(...args)
436 })
437β
438 // For the bug to trigger, there needs to already be a query in the cache,
439 // with a dataUpdatedAt earlier than the dehydratedAt of the next query
440 const clientQueryClient = new QueryClient()
441 void clientQueryClient
442 .query({
443 queryKey: promiseKey,
444 queryFn: () => sleep(20).then(() => 'existing'),
445 })
446 .catch(noop)
447 await vi.advanceTimersByTimeAsync(20)
448β
449 const prefetchQueryClient = new QueryClient({
450 defaultOptions: {
451 dehydrate: {
452 shouldDehydrateQuery: () => true,
453 },
454 },
455 })
456 void prefetchQueryClient
457 .query({
458 queryKey: promiseKey,
459 queryFn: () =>
460 sleep(10).then(() => Promise.reject(new Error('Query failed'))),
461 })
462 .catch(noop)
463β
464 const dehydratedState = dehydrate(prefetchQueryClient)
465β
466 // Mimic what React/our synchronous thenable does for already rejected promises
467 // @ts-expect-error
468 dehydratedState.queries[0].promise.status = 'failure'
469β
470 function Page() {
471 const { data } = useQuery({
472 queryKey: promiseKey,
473 queryFn: () => sleep(20).then(() => ['new']),
474 })
475 return (
476 <div>
477 <h1>{data}</h1>
478 </div>
479 )
480 }
481β
482 const rendered = render(
483 <QueryClientProvider client={clientQueryClient}>
484 <HydrationBoundary state={dehydratedState}>
485 <Page />
486 </HydrationBoundary>
487 </QueryClientProvider>,
488 )
489β
490 expect(rendered.getByText('existing')).toBeInTheDocument()
491 await vi.advanceTimersByTimeAsync(21)
492 expect(rendered.getByText('new')).toBeInTheDocument()
493β
494 prefetchQueryClient.clear()
495 clientQueryClient.clear()
496 })
497})