Query Docs
Guides & Concepts
- Important Defaults
- Queries
- Query Keys
- Query Functions
- Network Mode
- Parallel Queries
- Dependent Queries
- Background Fetching Indicators
- Window Focus Refetching
- Disabling/Pausing Queries
- Query Retries
- Paginated Queries
- Infinite Queries
- Initial Query Data
- Placeholder Query Data
- Prefetching
- Mutations
- Query Invalidation
- Invalidation from Mutations
- Updates from Mutation
- Optimistic Updates
- Query Cancellation
- Scroll Restoration
- Filters
- SSR & Nuxt
- Caching
- Default Query Fn
- Suspense
- Custom Logger
- Custom Client
- Does this replace [Vuex, Pinia]?
AI/LLM: This documentation page is available in plain markdown format at/query/v4/docs/framework/vue/guides/prefetching.md
Guides & Concepts
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:
tsx
const prefetchTodos = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
}- 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 no instances of useQuery appear for a prefetched query, it will be deleted and garbage collected after the time specified in cacheTime.
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 to directly add or update a query's cached result by key.
tsx
queryClient.setQueryData(['todos'], todos)Further reading#
For a deep-dive on how to get data into your Query Cache before you fetch, have a look at #17: Seeding the Query Cache from the Community Resources.