Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(infiniteQuery): allow prefetching arbitrary amounts of pages #5440

Merged
merged 11 commits into from
Jun 17, 2023
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 @@ -324,7 +324,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 @@ -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', () => {
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 @@ -359,20 +359,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>
}
Comment on lines +362 to +366
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you pass pages, you also need to pass getNextPageParam, because it's needed to fetch more than one page.

One thing I'm unsure about is the generic name pages. Maybe it should be more specific, like pagesAmount or so ? Thoughs?


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