Open History to see the last commit
1import { waitFor, fireEvent } from '@testing-library/react'
2import React from 'react'
3β
4import * as QueriesObserverModule from '../../core/queriesObserver'
5β
6import {
7 expectType,
8 expectTypeNotAny,
9 queryKey,
10 renderWithClient,
11 setActTimeout,
12 sleep,
13} from './utils'
14import {
15 useQueries,
16 QueryClient,
17 UseQueryResult,
18 QueryCache,
19 QueryObserverResult,
20 QueriesObserver,
21} from '../..'
22β
23describe('useQueries', () => {
24 const queryCache = new QueryCache()
25 const queryClient = new QueryClient({ queryCache })
26β
27 it('should return the correct states', async () => {
28 const key1 = queryKey()
29 const key2 = queryKey()
30 const results: UseQueryResult[][] = []
31β
32 function Page() {
33 const result = useQueries([
34 {
35 queryKey: key1,
36 queryFn: async () => {
37 await sleep(5)
38 return 1
39 },
40 },
41 {
42 queryKey: key2,
43 queryFn: async () => {
44 await sleep(10)
45 return 2
46 },
47 },
48 ])
49 results.push(result)
50 return null
51 }
52β
53 renderWithClient(queryClient, <Page />)
54β
55 await sleep(30)
56β
57 expect(results.length).toBe(3)
58 expect(results[0]).toMatchObject([{ data: undefined }, { data: undefined }])
59 expect(results[1]).toMatchObject([{ data: 1 }, { data: undefined }])
60 expect(results[2]).toMatchObject([{ data: 1 }, { data: 2 }])
61 })
62β
63 it('should keep previous data if amount of queries is the same', async () => {
64 const key1 = queryKey()
65 const key2 = queryKey()
66 const states: UseQueryResult[][] = []
67β
68 function Page() {
69 const [count, setCount] = React.useState(1)
70 const result = useQueries([
71 {
72 queryKey: [key1, count],
73 keepPreviousData: true,
74 queryFn: async () => {
75 await sleep(5)
76 return count * 2
77 },
78 },
79 {
80 queryKey: [key2, count],
81 keepPreviousData: true,
82 queryFn: async () => {
83 await sleep(10)
84 return count * 5
85 },
86 },
87 ])
88 states.push(result)
89β
90 React.useEffect(() => {
91 setActTimeout(() => {
92 setCount(prev => prev + 1)
93 }, 20)
94 }, [])
95β
96 return null
97 }
98β
99 renderWithClient(queryClient, <Page />)
100β
101 await waitFor(() => expect(states.length).toBe(7))
102β
103 expect(states[0]).toMatchObject([
104 {
105 status: 'loading',
106 data: undefined,
107 isPreviousData: false,
108 isFetching: true,
109 },
110 {
111 status: 'loading',
112 data: undefined,
113 isPreviousData: false,
114 isFetching: true,
115 },
116 ])
117 expect(states[1]).toMatchObject([
118 { status: 'success', data: 2, isPreviousData: false, isFetching: false },
119 {
120 status: 'loading',
121 data: undefined,
122 isPreviousData: false,
123 isFetching: true,
124 },
125 ])
126 expect(states[2]).toMatchObject([
127 { status: 'success', data: 2, isPreviousData: false, isFetching: false },
128 { status: 'success', data: 5, isPreviousData: false, isFetching: false },
129 ])
130 expect(states[3]).toMatchObject([
131 { status: 'success', data: 2, isPreviousData: true, isFetching: true },
132 { status: 'success', data: 5, isPreviousData: true, isFetching: true },
133 ])
134 expect(states[4]).toMatchObject([
135 { status: 'success', data: 2, isPreviousData: true, isFetching: true },
136 { status: 'success', data: 5, isPreviousData: true, isFetching: true },
137 ])
138 expect(states[5]).toMatchObject([
139 { status: 'success', data: 4, isPreviousData: false, isFetching: false },
140 { status: 'success', data: 5, isPreviousData: true, isFetching: true },
141 ])
142 expect(states[6]).toMatchObject([
143 { status: 'success', data: 4, isPreviousData: false, isFetching: false },
144 { status: 'success', data: 10, isPreviousData: false, isFetching: false },
145 ])
146 })
147β
148 it('should keep previous data for variable amounts of useQueries', async () => {
149 const key = queryKey()
150 const states: UseQueryResult[][] = []
151β
152 function Page() {
153 const [count, setCount] = React.useState(2)
154 const result = useQueries(
155 Array.from({ length: count }, (_, i) => ({
156 queryKey: [key, count, i + 1],
157 keepPreviousData: true,
158 queryFn: async () => {
159 await sleep(5 * (i + 1))
160 return (i + 1) * count * 2
161 },
162 }))
163 )
164β
165 states.push(result)
166β
167 React.useEffect(() => {
168 setActTimeout(() => {
169 setCount(prev => prev + 1)
170 }, 20)
171 }, [])
172β
173 return null
174 }
175β
176 renderWithClient(queryClient, <Page />)
177β
178 await waitFor(() => expect(states.length).toBe(8))
179β
180 expect(states[0]).toMatchObject([
181 {
182 status: 'loading',
183 data: undefined,
184 isPreviousData: false,
185 isFetching: true,
186 },
187 {
188 status: 'loading',
189 data: undefined,
190 isPreviousData: false,
191 isFetching: true,
192 },
193 ])
194 expect(states[1]).toMatchObject([
195 { status: 'success', data: 4, isPreviousData: false, isFetching: false },
196 {
197 status: 'loading',
198 data: undefined,
199 isPreviousData: false,
200 isFetching: true,
201 },
202 ])
203 expect(states[2]).toMatchObject([
204 { status: 'success', data: 4, isPreviousData: false, isFetching: false },
205 { status: 'success', data: 8, isPreviousData: false, isFetching: false },
206 ])
207β
208 expect(states[3]).toMatchObject([
209 { status: 'success', data: 4, isPreviousData: true, isFetching: true },
210 { status: 'success', data: 8, isPreviousData: true, isFetching: true },
211 {
212 status: 'loading',
213 data: undefined,
214 isPreviousData: false,
215 isFetching: true,
216 },
217 ])
218 expect(states[4]).toMatchObject([
219 { status: 'success', data: 4, isPreviousData: true, isFetching: true },
220 { status: 'success', data: 8, isPreviousData: true, isFetching: true },
221 {
222 status: 'loading',
223 data: undefined,
224 isPreviousData: false,
225 isFetching: true,
226 },
227 ])
228 expect(states[5]).toMatchObject([
229 { status: 'success', data: 6, isPreviousData: false, isFetching: false },
230 { status: 'success', data: 8, isPreviousData: true, isFetching: true },
231 {
232 status: 'loading',
233 data: undefined,
234 isPreviousData: false,
235 isFetching: true,
236 },
237 ])
238 expect(states[6]).toMatchObject([
239 { status: 'success', data: 6, isPreviousData: false, isFetching: false },
240 { status: 'success', data: 12, isPreviousData: false, isFetching: false },
241 {
242 status: 'loading',
243 data: undefined,
244 isPreviousData: false,
245 isFetching: true,
246 },
247 ])
248 expect(states[7]).toMatchObject([
249 { status: 'success', data: 6, isPreviousData: false, isFetching: false },
250 { status: 'success', data: 12, isPreviousData: false, isFetching: false },
251 { status: 'success', data: 18, isPreviousData: false, isFetching: false },
252 ])
253 })
254β
255 it('handles type parameter - tuple of tuples', async () => {
256 const key1 = queryKey()
257 const key2 = queryKey()
258 const key3 = queryKey()
259β
260 // @ts-expect-error (Page component is not rendered)
261 // eslint-disable-next-line
262 function Page() {
263 const result1 = useQueries<[[number], [string], [string[], boolean]]>([
264 {
265 queryKey: key1,
266 queryFn: () => 1,
267 },
268 {
269 queryKey: key2,
270 queryFn: () => 'string',
271 },
272 {
273 queryKey: key3,
274 queryFn: () => ['string[]'],
275 },
276 ])
277 expectType<QueryObserverResult<number, unknown>>(result1[0])
278 expectType<QueryObserverResult<string, unknown>>(result1[1])
279 expectType<QueryObserverResult<string[], boolean>>(result1[2])
280 expectType<number | undefined>(result1[0].data)
281 expectType<string | undefined>(result1[1].data)
282 expectType<string[] | undefined>(result1[2].data)
283 expectType<boolean | null>(result1[2].error)
284β
285 // TData (3rd element) takes precedence over TQueryFnData (1st element)
286 const result2 = useQueries<
287 [[string, unknown, string], [string, unknown, number]]
288 >([
289 {
290 queryKey: key1,
291 queryFn: () => 'string',
292 select: a => {
293 expectType<string>(a)
294 expectTypeNotAny(a)
295 return a.toLowerCase()
296 },
297 },
298 {
299 queryKey: key2,
300 queryFn: () => 'string',
301 select: a => {
302 expectType<string>(a)
303 expectTypeNotAny(a)
304 return parseInt(a)
305 },
306 },
307 ])
308 expectType<QueryObserverResult<string, unknown>>(result2[0])
309 expectType<QueryObserverResult<number, unknown>>(result2[1])
310 expectType<string | undefined>(result2[0].data)
311 expectType<number | undefined>(result2[1].data)
312β
313 // types should be enforced
314 useQueries<[[string, unknown, string], [string, boolean, number]]>([
315 {
316 queryKey: key1,
317 queryFn: () => 'string',
318 select: a => {
319 expectType<string>(a)
320 expectTypeNotAny(a)
321 return a.toLowerCase()
322 },
323 onSuccess: a => {
324 expectType<string>(a)
325 expectTypeNotAny(a)
326 },
327 placeholderData: 'string',
328 // @ts-expect-error (initialData: string)
329 initialData: 123,
330 },
331 {
332 queryKey: key2,
333 queryFn: () => 'string',
334 select: a => {
335 expectType<string>(a)
336 expectTypeNotAny(a)
337 return parseInt(a)
338 },
339 onSuccess: a => {
340 expectType<number>(a)
341 expectTypeNotAny(a)
342 },
343 onError: e => {
344 expectType<boolean>(e)
345 expectTypeNotAny(e)
346 },
347 placeholderData: 'string',
348 // @ts-expect-error (initialData: string)
349 initialData: 123,
350 },
351 ])
352β
353 // field names should be enforced
354 useQueries<[[string]]>([
355 {
356 queryKey: key1,
357 queryFn: () => 'string',
358 // @ts-expect-error (invalidField)
359 someInvalidField: [],
360 },
361 ])
362 }
363 })
364β
365 it('handles type parameter - tuple of objects', async () => {
366 const key1 = queryKey()
367 const key2 = queryKey()
368 const key3 = queryKey()
369β
370 // @ts-expect-error (Page component is not rendered)
371 // eslint-disable-next-line
372 function Page() {
373 const result1 = useQueries<
374 [
375 { queryFnData: number },
376 { queryFnData: string },
377 { queryFnData: string[]; error: boolean }
378 ]
379 >([
380 {
381 queryKey: key1,
382 queryFn: () => 1,
383 },
384 {
385 queryKey: key2,
386 queryFn: () => 'string',
387 },
388 {
389 queryKey: key3,
390 queryFn: () => ['string[]'],
391 },
392 ])
393 expectType<QueryObserverResult<number, unknown>>(result1[0])
394 expectType<QueryObserverResult<string, unknown>>(result1[1])
395 expectType<QueryObserverResult<string[], boolean>>(result1[2])
396 expectType<number | undefined>(result1[0].data)
397 expectType<string | undefined>(result1[1].data)
398 expectType<string[] | undefined>(result1[2].data)
399 expectType<boolean | null>(result1[2].error)
400β
401 // TData (data prop) takes precedence over TQueryFnData (queryFnData prop)
402 const result2 = useQueries<
403 [
404 { queryFnData: string; data: string },
405 { queryFnData: string; data: number }
406 ]
407 >([
408 {
409 queryKey: key1,
410 queryFn: () => 'string',
411 select: a => {
412 expectType<string>(a)
413 expectTypeNotAny(a)
414 return a.toLowerCase()
415 },
416 },
417 {
418 queryKey: key2,
419 queryFn: () => 'string',
420 select: a => {
421 expectType<string>(a)
422 expectTypeNotAny(a)
423 return parseInt(a)
424 },
425 },
426 ])
427 expectType<QueryObserverResult<string, unknown>>(result2[0])
428 expectType<QueryObserverResult<number, unknown>>(result2[1])
429 expectType<string | undefined>(result2[0].data)
430 expectType<number | undefined>(result2[1].data)
431β
432 // can pass only TData (data prop) although TQueryFnData will be left unknown
433 const result3 = useQueries<[{ data: string }, { data: number }]>([
434 {
435 queryKey: key1,
436 queryFn: () => 'string',
437 select: a => {
438 expectType<unknown>(a)
439 expectTypeNotAny(a)
440 return a as string
441 },
442 },
443 {
444 queryKey: key2,
445 queryFn: () => 'string',
446 select: a => {
447 expectType<unknown>(a)
448 expectTypeNotAny(a)
449 return a as number
450 },
451 },
452 ])
453 expectType<QueryObserverResult<string, unknown>>(result3[0])
454 expectType<QueryObserverResult<number, unknown>>(result3[1])
455 expectType<string | undefined>(result3[0].data)
456 expectType<number | undefined>(result3[1].data)
457β
458 // types should be enforced
459 useQueries<
460 [
461 { queryFnData: string; data: string },
462 { queryFnData: string; data: number; error: boolean }
463 ]
464 >([
465 {
466 queryKey: key1,
467 queryFn: () => 'string',
468 select: a => {
469 expectType<string>(a)
470 expectTypeNotAny(a)
471 return a.toLowerCase()
472 },
473 onSuccess: a => {
474 expectType<string>(a)
475 expectTypeNotAny(a)
476 },
477 placeholderData: 'string',
478 // @ts-expect-error (initialData: string)
479 initialData: 123,
480 },
481 {
482 queryKey: key2,
483 queryFn: () => 'string',
484 select: a => {
485 expectType<string>(a)
486 expectTypeNotAny(a)
487 return parseInt(a)
488 },
489 onSuccess: a => {
490 expectType<number>(a)
491 expectTypeNotAny(a)
492 },
493 onError: e => {
494 expectType<boolean>(e)
495 expectTypeNotAny(e)
496 },
497 placeholderData: 'string',
498 // @ts-expect-error (initialData: string)
499 initialData: 123,
500 },
501 ])
502β
503 // field names should be enforced
504 useQueries<[{ queryFnData: string }]>([
505 {
506 queryKey: key1,
507 queryFn: () => 'string',
508 // @ts-expect-error (invalidField)
509 someInvalidField: [],
510 },
511 ])
512 }
513 })
514β
515 it('handles array literal without type parameter to infer result type', async () => {
516 const key1 = queryKey()
517 const key2 = queryKey()
518 const key3 = queryKey()
519 const key4 = queryKey()
520β
521 // @ts-expect-error (Page component is not rendered)
522 // eslint-disable-next-line
523 function Page() {
524 // Array.map preserves TQueryFnData
525 const result1 = useQueries(
526 Array(50).map((_, i) => ({
527 queryKey: ['key', i] as const,
528 queryFn: () => i + 10,
529 }))
530 )
531 expectType<QueryObserverResult<number, unknown>[]>(result1)
532 expectType<number | undefined>(result1[0]?.data)
533β
534 // Array.map preserves TData
535 const result2 = useQueries(
536 Array(50).map((_, i) => ({
537 queryKey: ['key', i] as const,
538 queryFn: () => i + 10,
539 select: (data: number) => data.toString(),
540 }))
541 )
542 expectType<QueryObserverResult<string, unknown>[]>(result2)
543β
544 const result3 = useQueries([
545 {
546 queryKey: key1,
547 queryFn: () => 1,
548 },
549 {
550 queryKey: key2,
551 queryFn: () => 'string',
552 },
553 {
554 queryKey: key3,
555 queryFn: () => ['string[]'],
556 select: () => 123,
557 },
558 ])
559 expectType<QueryObserverResult<number, unknown>>(result3[0])
560 expectType<QueryObserverResult<string, unknown>>(result3[1])
561 expectType<QueryObserverResult<number, unknown>>(result3[2])
562 expectType<number | undefined>(result3[0].data)
563 expectType<string | undefined>(result3[1].data)
564 // select takes precedence over queryFn
565 expectType<number | undefined>(result3[2].data)
566β
567 // initialData/placeholderData are enforced
568 useQueries([
569 {
570 queryKey: key1,
571 queryFn: () => 'string',
572 placeholderData: 'string',
573 // @ts-expect-error (initialData: string)
574 initialData: 123,
575 },
576 {
577 queryKey: key2,
578 queryFn: () => 123,
579 // @ts-expect-error (placeholderData: number)
580 placeholderData: 'string',
581 initialData: 123,
582 },
583 ])
584β
585 // select / onSuccess / onSettled params are "indirectly" enforced
586 useQueries([
587 // unfortunately TS will not suggest the type for you
588 {
589 queryKey: key1,
590 queryFn: () => 'string',
591 // @ts-expect-error (noImplicitAny)
592 onSuccess: a => null,
593 // @ts-expect-error (noImplicitAny)
594 onSettled: a => null,
595 },
596 // however you can add a type to the callback
597 {
598 queryKey: key2,
599 queryFn: () => 'string',
600 onSuccess: (a: string) => {
601 expectType<string>(a)
602 expectTypeNotAny(a)
603 },
604 onSettled: (a: string | undefined) => {
605 expectType<string | undefined>(a)
606 expectTypeNotAny(a)
607 },
608 },
609 // the type you do pass is enforced
610 {
611 queryKey: key3,
612 queryFn: () => 'string',
613 // @ts-expect-error (only accepts string)
614 onSuccess: (a: number) => null,
615 },
616 {
617 queryKey: key4,
618 queryFn: () => 'string',
619 select: (a: string) => parseInt(a),
620 // @ts-expect-error (select is defined => only accepts number)
621 onSuccess: (a: string) => null,
622 onSettled: (a: number | undefined) => {
623 expectType<number | undefined>(a)
624 expectTypeNotAny(a)
625 },
626 },
627 ])
628β
629 // callbacks are also indirectly enforced with Array.map
630 useQueries(
631 // @ts-expect-error (onSuccess only accepts string)
632 Array(50).map((_, i) => ({
633 queryKey: ['key', i] as const,
634 queryFn: () => i + 10,
635 select: (data: number) => data.toString(),
636 onSuccess: (_data: number) => null,
637 }))
638 )
639 useQueries(
640 Array(50).map((_, i) => ({
641 queryKey: ['key', i] as const,
642 queryFn: () => i + 10,
643 select: (data: number) => data.toString(),
644 onSuccess: (_data: string) => null,
645 }))
646 )
647β
648 // results inference works when all the handlers are defined
649 const result4 = useQueries([
650 {
651 queryKey: key1,
652 queryFn: () => 'string',
653 // @ts-expect-error (noImplicitAny)
654 onSuccess: a => null,
655 // @ts-expect-error (noImplicitAny)
656 onSettled: a => null,
657 },
658 {
659 queryKey: key2,
660 queryFn: () => 'string',
661 onSuccess: (a: string) => {
662 expectType<string>(a)
663 expectTypeNotAny(a)
664 },
665 onSettled: (a: string | undefined) => {
666 expectType<string | undefined>(a)
667 expectTypeNotAny(a)
668 },
669 },
670 {
671 queryKey: key4,
672 queryFn: () => 'string',
673 select: (a: string) => parseInt(a),
674 onSuccess: (_a: number) => null,
675 onSettled: (a: number | undefined) => {
676 expectType<number | undefined>(a)
677 expectTypeNotAny(a)
678 },
679 },
680 ])
681 expectType<QueryObserverResult<string, unknown>>(result4[0])
682 expectType<QueryObserverResult<string, unknown>>(result4[1])
683 expectType<QueryObserverResult<number, unknown>>(result4[2])
684β
685 // Array as const does not throw error
686 const result5 = useQueries([
687 {
688 queryKey: 'key1',
689 queryFn: () => 'string',
690 },
691 {
692 queryKey: 'key1',
693 queryFn: () => 123,
694 },
695 ] as const)
696 expectType<QueryObserverResult<string, unknown>>(result5[0])
697 expectType<QueryObserverResult<number, unknown>>(result5[1])
698β
699 // field names should be enforced - array literal
700 useQueries([
701 {
702 queryKey: key1,
703 queryFn: () => 'string',
704 // @ts-expect-error (invalidField)
705 someInvalidField: [],
706 },
707 ])
708β
709 // field names should be enforced - Array.map() result
710 useQueries(
711 // @ts-expect-error (invalidField)
712 Array(10).map(() => ({
713 someInvalidField: '',
714 }))
715 )
716 }
717 })
718β
719 it('should not change state if unmounted', async () => {
720 const key1 = queryKey()
721β
722 // We have to mock the QueriesObserver to not unsubscribe
723 // the listener when the component is unmounted
724 class QueriesObserverMock extends QueriesObserver {
725 subscribe(listener: any) {
726 super.subscribe(listener)
727 return () => void 0
728 }
729 }
730β
731 const QueriesObserverSpy = jest
732 .spyOn(QueriesObserverModule, 'QueriesObserver')
733 .mockImplementation(fn => {
734 return new QueriesObserverMock(fn)
735 })
736β
737 function Queries() {
738 useQueries([
739 {
740 queryKey: key1,
741 queryFn: async () => {
742 await sleep(10)
743 return 1
744 },
745 },
746 ])
747β
748 return (
749 <div>
750 <span>queries</span>
751 </div>
752 )
753 }
754β
755 function Page() {
756 const [mounted, setMounted] = React.useState(true)
757β
758 return (
759 <div>
760 <button onClick={() => setMounted(false)}>unmount</button>
761 {mounted && <Queries />}
762 </div>
763 )
764 }
765β
766 const { getByText } = renderWithClient(queryClient, <Page />)
767 fireEvent.click(getByText('unmount'))
768β
769 // Should not display the console error
770 // "Warning: Can't perform a React state update on an unmounted component"
771β
772 await sleep(20)
773 QueriesObserverSpy.mockRestore()
774 })
775})