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, use queryClient.query or queryClient.infiniteQuery to warm the cache ahead of time:
import { noop } from '@tanstack/vue-query'
const prefetchTodos = async () => {
// The results of this query will be cached like a normal query
await queryClient
.query({
queryKey: ['todos'],
queryFn: fetchTodos,
})
.catch(noop)
}Pass getNextPageParam when you prefetch an infinite query. On an empty cache, the client fetches the first page by default. Use pages to request more pages. If the cache already contains stale pages and you omit pages, the client refetches up to the number of cached pages.
import { noop } from '@tanstack/vue-query'
const prefetchProjects = async () => {
// The results of this query will be cached like a normal query
await queryClient
.infiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
pages: 3, // prefetch the first 3 pages
})
.catch(noop)
}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.