Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

prefetching.md

57 lines2.3 KB

1---
2id: prefetching
3title: Prefetching
4---
5​
6If 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, use `queryClient.query` or `queryClient.infiniteQuery` to warm the cache ahead of time:
7​
8[//]: # 'ExamplePrefetching'
9​
10```tsx
11import { noop } from '@tanstack/vue-query'
12​
13const prefetchTodos = async () => {
14 // The results of this query will be cached like a normal query
15 await queryClient
16 .query({
17 queryKey: ['todos'],
18 queryFn: fetchTodos,
19 })
20 .catch(noop)
22```
23​
24[//]: # 'ExamplePrefetching'
25​
26- If **fresh** data for this query is already in the cache, the data will not be fetched
27- If a `staleTime` is passed e.g. `queryClient.query({ queryKey: ['todos'], queryFn: fn, staleTime: 5 * 1000 })` and the data is older than the specified `staleTime`, the query will be fetched
28- As `useQuery` will retry fetches and handle errors, you can use `void` to ignore the promise from `query` and `.catch(noop)` to ignore errors.
29- If you want to always return cached data when it exists, use `staleTime: 'static'`
30- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `gcTime`.
31​
32## Prefetching Infinite Queries
33​
34Infinite 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:
35​
36[//]: # 'ExampleInfiniteQuery'
37​
38```tsx
39import { noop } from '@tanstack/vue-query'
40​
41const prefetchProjects = async () => {
42 // The results of this query will be cached like a normal query
43 await queryClient
44 .infiniteQuery({
45 queryKey: ['projects'],
46 queryFn: fetchProjects,
47 initialPageParam: 0,
48 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
49 pages: 3, // prefetch the first 3 pages
50 })
51 .catch(noop)
53```
54​
55[//]: # 'ExampleInfiniteQuery'
56​
57The 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.