Skip to content

Commit

Permalink
feat(infiniteQuery): allow prefetching arbitrary amounts of pages (#5440
Browse files Browse the repository at this point in the history
)

* refactor: combine fetching first page with refetching

as it's the same condition

* feat(infiniteQuery): allow prefetching arbitrary amounts of pages

* test prefetching

* fix: make sure that pages and getNextPageParam are passed in tandem to (pre)fetchInfiniteQuery

* docs: prefetching

* chore: try to stabilize test

* docs: migration guide
  • Loading branch information
TkDodo authored Jun 17, 2023
1 parent 772e55d commit 3e009d3
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 33 deletions.
4 changes: 4 additions & 0 deletions docs/react/guides/migrating-to-v5.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 27 additions & 6 deletions docs/react/guides/prefetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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'

Expand Down
29 changes: 12 additions & 17 deletions packages/query-core/src/infiniteQueryBehavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ import type {
QueryKey,
} from './types'

export function infiniteQueryBehavior<
TQueryFnData,
TError,
TData,
>(): QueryBehavior<TQueryFnData, TError, InfiniteData<TData>> {
export function infiniteQueryBehavior<TQueryFnData, TError, TData>(
pages?: number,
): QueryBehavior<TQueryFnData, TError, InfiniteData<TData>> {
return {
onFetch: (context) => {
context.fetchFn = async () => {
Expand Down Expand Up @@ -84,13 +82,8 @@ export function infiniteQueryBehavior<

let result: InfiniteData<unknown>

// 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 = {
Expand All @@ -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)
}
Expand Down
4 changes: 3 additions & 1 deletion packages/query-core/src/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,9 @@ export class QueryClient {
TPageParam
>,
): Promise<InfiniteData<TData>> {
options.behavior = infiniteQueryBehavior<TQueryFnData, TError, TData>()
options.behavior = infiniteQueryBehavior<TQueryFnData, TError, TData>(
options.pages,
)
return this.fetchQuery(options)
}

Expand Down
40 changes: 40 additions & 0 deletions packages/query-core/src/tests/queryClient.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
26 changes: 17 additions & 9 deletions packages/query-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,20 +358,28 @@ export interface FetchQueryOptions<
staleTime?: number
}

export interface FetchInfiniteQueryOptions<
type FetchInfiniteQueryPages<TQueryFnData = unknown, TPageParam = unknown> =
| { pages?: never; getNextPageParam?: never }
| {
pages: number
getNextPageParam: GetNextPageParamFunction<TPageParam, TQueryFnData>
}

export type FetchInfiniteQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> extends FetchQueryOptions<
TQueryFnData,
TError,
InfiniteData<TData>,
TQueryKey,
TPageParam
>,
DefaultPageParam<TPageParam> {}
> = FetchQueryOptions<
TQueryFnData,
TError,
InfiniteData<TData>,
TQueryKey,
TPageParam
> &
DefaultPageParam<TPageParam> &
FetchInfiniteQueryPages<TQueryFnData, TPageParam>

export interface ResultOptions {
throwOnError?: boolean
Expand Down

0 comments on commit 3e009d3

Please sign in to comment.