Vue Query - Basic
As you visit the posts below, you will notice them in a loading state the
first time you load them. However, after you return to this list and click
on any posts you have already visited again, you will see them load
instantly and background refresh right before your eyes!
(You may need to throttle your network speed to simulate longer loading
sequences)
```
--------------------------------
### Using Fetch with Multiple Cancellable Requests
Source: https://tanstack.com/query/latest/docs/framework/vue/guides/query-cancellation.md
Demonstrates passing an AbortSignal to multiple fetch requests within a single query function. This allows for cancellation of all ongoing requests if the query is cancelled.
```tsx
const query = useQuery({
queryKey: ['todos'],
queryFn: async ({ signal }) => {
const todosResponse = await fetch('/todos', {
// Pass the signal to one fetch
signal,
})
const todos = await todosResponse.json()
const todoDetails = todos.map(async ({ details }) => {
const response = await fetch(details, {
// Or pass it to several
signal,
})
return response.json()
})
return Promise.all(todoDetails)
},
})
```
--------------------------------
### Nuxt Kit Production Dependencies
Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3
This snippet details the production dependencies for the Nuxt Kit package, including c12, consola, defu, destr, errx, exsolve, ignore, jiti, klona, mlly, ohash, pathe, pkg-types, rc9, scule, semver, tinyglobby, ufo, unctx, and untyped. It specifies Node.js version requirements.
```json
{
"version": "4.4.7",
"resolved": "https://registry.npmjs.org/@nuxt/kit/-/kit-4.4.7.tgz",
"integrity": "sha512-QwtpqNxSOLyJH1UoDpcgsfzVEw95J0893hn1A+CvgeOxoTos1BGvD15D1v/OVQ2MK1EpfnFZJby51t1yudOvBA==",
"dev": true,
"dependencies": {
"c12": "^3.3.4",
"consola": "^3.4.2",
"defu": "^6.1.7",
"destr": "^2.0.5",
"errx": "^0.1.0",
"exsolve": "^1.0.8",
"ignore": "^7.0.5",
"jiti": "^2.7.0",
"klona": "^2.0.6",
"mlly": "^1.8.2",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"pkg-types": "^2.3.1",
"rc9": "^3.0.1",
"scule": "^1.3.0",
"semver": "^7.8.1",
"tinyglobby": "^0.2.17",
"ufo": "^1.6.4",
"unctx": "^2.5.0",
"untyped": "^2.0.0"
},
"engines": {
"node": ">=18.12.0"
}
}
```
--------------------------------
### Use Custom QueryClient Key in Query Options
Source: https://tanstack.com/query/latest/docs/framework/vue/guides/custom-client.md
When using a custom context key, specify it within the query options to ensure the correct QueryClient is used.
```javascript
useQuery({
queryKey: ['query1'],
queryFn: fetcher,
queryClientKey: 'foo',
})
```
--------------------------------
### Conditionally Fetch Initial Data from Cache
Source: https://tanstack.com/query/latest/docs/framework/vue/guides/initial-query-data.md
Conditionally provide initial data from the cache based on its freshness. Use `queryClient.getQueryState` to check the `dataUpdatedAt` timestamp and decide if the cached data is recent enough (e.g., not older than 10 seconds). If not, return `undefined` to trigger a fetch.
```tsx
const result = useQuery({
queryKey: ['todo', todoId],
queryFn: () => fetch(`/todos/${todoId}`),
initialData: () => {
// Get the query state
const state = queryClient.getQueryState(['todos'])
// If the query exists and has data that is no older than 10 seconds...
if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) {
// return the individual todo
return state.data.find((d) => d.id === todoId)
}
// Otherwise, return undefined and let it fetch from a hard loading state!
},
})
```
--------------------------------
### Initial Data from a Function
Source: https://tanstack.com/query/latest/docs/framework/vue/guides/initial-query-data.md
Provide a function to the `initialData` option to execute the data fetching logic only once during query initialization. This is useful for computationally expensive data retrieval.
```tsx
const result = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/todos'),
initialData: () => getExpensiveTodos(),
})
```
--------------------------------
### Display Individual Query Background Fetching State in Vue
Source: https://tanstack.com/query/latest/docs/framework/vue/guides/background-fetching-indicators.md
Use the `isFetching` boolean from `useQuery` to show an indicator when a query is refetching in the background, regardless of its `status`. Ensure `getTodos` is defined elsewhere.
```vue