From 544b409877d08fca2f2b4a0dd54a24e277366a25 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 19 May 2023 09:52:28 +0200 Subject: [PATCH 1/7] refactor: combine fetching first page with refetching as it's the same condition --- .../query-core/src/infiniteQueryBehavior.ts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index eb270de42b..fed9c62ece 100644 --- a/packages/query-core/src/infiniteQueryBehavior.ts +++ b/packages/query-core/src/infiniteQueryBehavior.ts @@ -84,13 +84,8 @@ export function infiniteQueryBehavior< let result: InfiniteData - // Fetch first page? - if (!oldPages.length) { - result = await fetchPage(empty, options.defaultPageParam) - } - // fetch next / previous page? - else if (direction) { + if (direction && oldPages.length) { const previous = direction === 'backward' const pageParamFn = previous ? getPreviousPageParam : getNextPageParam const oldData = { @@ -100,12 +95,12 @@ export function infiniteQueryBehavior< const param = pageParamFn(options, oldData) result = await fetchPage(oldData, param, previous) - } - - // Refetch pages - else { + } else { // Fetch first page - result = await fetchPage(empty, oldPageParams[0]) + result = await fetchPage( + empty, + oldPageParams[0] ?? options.defaultPageParam, + ) // Fetch remaining pages for (let i = 1; i < oldPages.length; i++) { From aadf81ffe98b6c7f1402bf1a79e0e1d299a73a3d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Fri, 19 May 2023 09:54:50 +0200 Subject: [PATCH 2/7] feat(infiniteQuery): allow prefetching arbitrary amounts of pages --- packages/query-core/src/infiniteQueryBehavior.ts | 12 ++++++------ packages/query-core/src/queryClient.ts | 4 +++- packages/query-core/src/types.ts | 4 +++- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index fed9c62ece..639c805d16 100644 --- a/packages/query-core/src/infiniteQueryBehavior.ts +++ b/packages/query-core/src/infiniteQueryBehavior.ts @@ -7,11 +7,9 @@ import type { QueryKey, } from './types' -export function infiniteQueryBehavior< - TQueryFnData, - TError, - TData, ->(): QueryBehavior> { +export function infiniteQueryBehavior( + pages?: number, +): QueryBehavior> { return { onFetch: (context) => { context.fetchFn = async () => { @@ -102,8 +100,10 @@ export function infiniteQueryBehavior< oldPageParams[0] ?? options.defaultPageParam, ) + const remainingPages = pages ?? oldPages.length + // Fetch remaining pages - for (let i = 1; i < oldPages.length; i++) { + for (let i = 1; i < remainingPages; i++) { const param = getNextPageParam(options, result) result = await fetchPage(result, param) } diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index b8c1833a55..6f78f89a45 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -324,7 +324,9 @@ export class QueryClient { TPageParam >, ): Promise> { - options.behavior = infiniteQueryBehavior() + options.behavior = infiniteQueryBehavior( + options.pages, + ) return this.fetchQuery(options) } diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index b08c4d905e..ebcde68b51 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -372,7 +372,9 @@ export interface FetchInfiniteQueryOptions< TQueryKey, TPageParam >, - DefaultPageParam {} + DefaultPageParam { + pages?: number +} export interface ResultOptions { throwOnError?: boolean From b91496ce0091090d1251dd857bb98647fb4f340d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 20 May 2023 16:05:52 +0200 Subject: [PATCH 3/7] test prefetching --- .../query-core/src/tests/queryClient.test.tsx | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/packages/query-core/src/tests/queryClient.test.tsx b/packages/query-core/src/tests/queryClient.test.tsx index bde738afb8..4198369103 100644 --- a/packages/query-core/src/tests/queryClient.test.tsx +++ b/packages/query-core/src/tests/queryClient.test.tsx @@ -645,6 +645,46 @@ describe('queryClient', () => { pageParams: [10], }) }) + + test('should prefetch multiple pages', async () => { + const key = queryKey() + + await queryClient.prefetchInfiniteQuery({ + queryKey: key, + queryFn: ({ pageParam }) => String(pageParam), + getNextPageParam: (_lastPage, _pages, lastPageParam) => + lastPageParam + 5, + defaultPageParam: 10, + pages: 3, + }) + + const result = queryClient.getQueryData(key) + + expect(result).toEqual({ + pages: ['10', '15', '20'], + pageParams: [10, 15, 20], + }) + }) + + test('should stop prefetching if getNextPageParam returns undefined', async () => { + const key = queryKey() + + await queryClient.prefetchInfiniteQuery({ + queryKey: key, + queryFn: ({ pageParam }) => String(pageParam), + getNextPageParam: (_lastPage, _pages, lastPageParam) => + lastPageParam >= 20 ? undefined : lastPageParam + 5, + defaultPageParam: 10, + pages: 5, + }) + + const result = queryClient.getQueryData(key) + + expect(result).toEqual({ + pages: ['10', '15', '20'], + pageParams: [10, 15, 20], + }) + }) }) describe('prefetchQuery', () => { From 1ebb1a3fbac843699dc743c047f1074a4c56038a Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 20 May 2023 16:06:16 +0200 Subject: [PATCH 4/7] fix: make sure that pages and getNextPageParam are passed in tandem to (pre)fetchInfiniteQuery --- packages/query-core/src/types.ts | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index ebcde68b51..ebad99ae66 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -359,22 +359,28 @@ export interface FetchQueryOptions< staleTime?: number } -export interface FetchInfiniteQueryOptions< +type FetchInfiniteQueryPages = + | { pages?: never; getNextPageParam?: never } + | { + pages: number + getNextPageParam: GetNextPageParamFunction + } + +export type FetchInfiniteQueryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> extends FetchQueryOptions< - TQueryFnData, - TError, - InfiniteData, - TQueryKey, - TPageParam - >, - DefaultPageParam { - pages?: number -} +> = FetchQueryOptions< + TQueryFnData, + TError, + InfiniteData, + TQueryKey, + TPageParam +> & + DefaultPageParam & + FetchInfiniteQueryPages export interface ResultOptions { throwOnError?: boolean From d1b2411e9c0a4b89fab370bc1df711da4b7fa36d Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 20 May 2023 16:06:22 +0200 Subject: [PATCH 5/7] docs: prefetching --- docs/react/guides/prefetching.md | 33 ++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/react/guides/prefetching.md b/docs/react/guides/prefetching.md index b944f60dea..e3fbe793d6 100644 --- a/docs/react/guides/prefetching.md +++ b/docs/react/guides/prefetching.md @@ -5,7 +5,7 @@ title: Prefetching If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the `prefetchQuery` method to prefetch the results of a query to be placed into the cache: -[//]: # 'Example' +[//]: # 'ExamplePrefetching' ```tsx const prefetchTodos = async () => { @@ -17,23 +17,44 @@ const prefetchTodos = async () => { } ``` -[//]: # 'Example' +[//]: # 'ExamplePrefetching' -- If data for this query is already in the cache and **not invalidated**, the data will not be fetched -- If a `staleTime` is passed eg. `prefetchQuery({queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified staleTime, the query will be fetched +- If **fresh** data for this query is already in the cache, the data will not be fetched +- If a `staleTime` is passed eg. `prefetchQuery({ queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified `staleTime`, the query will be fetched - If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `gcTime`. +## Prefetching Infinite Queries + +Infinite Queries can be prefetched like regular Queries. Per default, only the first page of the Query will be prefetched and will be stored under the given QueryKey. If you want to prefetch more than one page, you can use the `pages` option, in which case you also have to provide a `getNextPageParam` function: + +[//]: # 'ExampleInfiniteQuery' +```tsx +const prefetchTodos = async () => { + // The results of this query will be cached like a normal query + await queryClient.prefetchInfiniteQuery({ + queryKey: ['projects'], + queryFn: fetchProjects, + defaultPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + pages: 3 // prefetch the first 3 pages + }) +} +``` +[//]: # 'ExampleInfiniteQuery' + +The above code will try to prefetch 3 pages in order, and `getNextPageParam` will be executed for each page to determine the next page to prefetch. If `getNextPageParam` returns `undefined`, the prefetching will stop. + ## Manually Priming a Query Alternatively, if you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [Query Client's `setQueryData` method](../reference/QueryClient#queryclientsetquerydata) to directly add or update a query's cached result by key. -[//]: # 'Example2' +[//]: # 'ExampleSetQueryData' ```tsx queryClient.setQueryData(['todos'], todos) ``` -[//]: # 'Example2' +[//]: # 'ExampleSetQueryData' [//]: # 'Materials' From a3b8d15c84684429e141685d7b0c0ae2dd4e7453 Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 20 May 2023 16:15:06 +0200 Subject: [PATCH 6/7] chore: try to stabilize test --- packages/react-query/src/__tests__/useQueries.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react-query/src/__tests__/useQueries.test.tsx b/packages/react-query/src/__tests__/useQueries.test.tsx index 8ddfa512be..11131e7e5f 100644 --- a/packages/react-query/src/__tests__/useQueries.test.tsx +++ b/packages/react-query/src/__tests__/useQueries.test.tsx @@ -905,14 +905,14 @@ describe('useQueries', () => { { queryKey: key1, queryFn: async () => { - await sleep(10) + await sleep(5) return Promise.resolve('first result ' + count) }, }, { queryKey: key2, queryFn: async () => { - await sleep(20) + await sleep(25) return Promise.resolve('second result ' + count) }, }, From 3e8b77db3e42f63a37c465de4950664638e9782f Mon Sep 17 00:00:00 2001 From: Dominik Dorfmeister Date: Sat, 17 Jun 2023 10:38:32 +0200 Subject: [PATCH 7/7] docs: migration guide --- docs/react/guides/migrating-to-v5.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/react/guides/migrating-to-v5.md b/docs/react/guides/migrating-to-v5.md index d418a15dc5..a1c4e8ada7 100644 --- a/docs/react/guides/migrating-to-v5.md +++ b/docs/react/guides/migrating-to-v5.md @@ -439,6 +439,10 @@ You can adjust the `maxPages` value according to the UX and refetching performan Note that the infinite list must be bi-directional, which requires both `getNextPageParam` and `getPreviousPageParam` to be defined. +### Infinite Queries can prefetch multiple pages + +Infinite Queries can be prefetched like regular Queries. Per default, only the first page of the Query will be prefetched and will be stored under the given QueryKey. If you want to prefetch more than one page, you can use the `pages` option. Read the [prefetching guide](../guides/prefetching) for more information. + ### Typesafe way to create Query Options See the [TypeScript docs](../typescript#typing-query-options) for more details.