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. 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' diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index eb270de42b..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 () => { @@ -84,13 +82,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,15 +93,17 @@ 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, + ) + + 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 b96b1eb26e..4ff29b5b32 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -325,7 +325,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/tests/queryClient.test.tsx b/packages/query-core/src/tests/queryClient.test.tsx index b29ddf67a2..82f2558abd 100644 --- a/packages/query-core/src/tests/queryClient.test.tsx +++ b/packages/query-core/src/tests/queryClient.test.tsx @@ -649,6 +649,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', () => { diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 248ff47f66..038952de68 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -358,20 +358,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 {} +> = FetchQueryOptions< + TQueryFnData, + TError, + InfiniteData, + TQueryKey, + TPageParam +> & + DefaultPageParam & + FetchInfiniteQueryPages export interface ResultOptions { throwOnError?: boolean