snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
Some checks failed
autofix.ci / autofix (push) Failing after 4s
Release / Release (push) Has been skipped
GitHub Actions Security Analysis / Run zizmor (push) Failing after 2s

This commit is contained in:
upstream-mirror
2026-09-16 01:13:08 +05:00
commit 3a013ccdfe
3570 changed files with 490194 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
---
id: defaultShouldDehydrateMutation
title: defaultShouldDehydrateMutation
---
```ts
function defaultShouldDehydrateMutation(mutation): boolean;
```
Defined in: [packages/query-core/src/hydration.ts:177](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L177)
The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
currently paused (e.g. paused by `networkMode` while offline).
## Parameters
### mutation
[`Mutation`](../classes/Mutation.md)
## Returns
`boolean`

View File

@@ -0,0 +1,23 @@
---
id: defaultShouldDehydrateQuery
title: defaultShouldDehydrateQuery
---
```ts
function defaultShouldDehydrateQuery(query): boolean;
```
Defined in: [packages/query-core/src/hydration.ts:185](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L185)
The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
`'success'`.
## Parameters
### query
[`Query`](../classes/Query.md)
## Returns
`boolean`

View File

@@ -0,0 +1,43 @@
---
id: dehydrate
title: dehydrate
---
```ts
function dehydrate(client, options): DehydratedState;
```
Defined in: [packages/query-core/src/hydration.ts:207](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L207)
Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
`defaultShouldDehydrateMutation`.
## Parameters
### client
`QueryClient`
### options
[`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}`
## Returns
[`DehydratedState`](../interfaces/DehydratedState.md)
## Example
```ts
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts,
})
const dehydratedState = dehydrate(queryClient)
```

View File

@@ -0,0 +1,43 @@
---
id: dehydrateQuery
title: dehydrateQuery
---
```ts
function dehydrateQuery(
query,
serializeData?,
shouldRedactErrors?): DehydratedQuery;
```
Defined in: [packages/query-core/src/hydration.ts:148](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L148)
Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
`queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
## Parameters
### query
[`Query`](../classes/Query.md)
The query to dehydrate.
### serializeData?
`TransformerFn`
Optional transform applied to `query.state.data` before it is included in the snapshot.
### shouldRedactErrors?
(`error`) => `boolean`
Optional predicate; if it returns `false` for the promise's rejection error, that
error is kept as-is instead of being redacted.
## Returns
`DehydratedQuery`

View File

@@ -0,0 +1,52 @@
---
id: experimental_streamedQuery
title: experimental_streamedQuery
---
```ts
function experimental_streamedQuery<TQueryFnData, TData, TQueryKey>(streamFn): QueryFunction<TData, TQueryKey>;
```
Defined in: [packages/query-core/src/streamedQuery.ts:75](https://github.com/TanStack/query/blob/main/packages/query-core/src/streamedQuery.ts#L75)
This is a helper function to create a query function that streams data from an AsyncIterable.
Data will be an Array of all the chunks received.
The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
The query will stay in fetchStatus 'fetching' until the stream ends.
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TData
`TData` = `TQueryFnData`[]
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
## Parameters
### streamFn
`StreamedQueryParams`\<`TQueryFnData`, `TData`, `TQueryKey`\>
The function that returns an AsyncIterable to stream data from.
## Returns
[`QueryFunction`](../type-aliases/QueryFunction.md)\<`TData`, `TQueryKey`\>
## Example
```ts
await queryClient.query({
queryKey: ['data'],
queryFn: streamedQuery({
streamFn: fetchDataInChunks,
}),
})
```

View File

@@ -0,0 +1,30 @@
---
id: hashKey
title: hashKey
---
```ts
function hashKey(queryKey): string;
```
Defined in: [packages/query-core/src/utils.ts:284](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L284)
Default query & mutation keys hash function.
Hashes the value into a stable hash.
## Parameters
### queryKey
readonly `unknown`[]
## Returns
`string`
## Example
```ts
// Object keys are sorted, so key order doesn't affect the hash:
hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
```

View File

@@ -0,0 +1,49 @@
---
id: hydrate
title: hydrate
---
```ts
function hydrate(
client,
dehydratedState,
options?): void;
```
Defined in: [packages/query-core/src/hydration.ts:264](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L264)
Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
`queryFn`.
## Parameters
### client
`QueryClient`
### dehydratedState
`Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\>
### options?
[`HydrateOptions`](../interfaces/HydrateOptions.md)
## Returns
`void`
## Example
```ts
// dehydratedState was produced by `dehydrate` on the server
// and sent to the client, e.g. embedded in server-rendered markup.
const queryClient = new QueryClient()
hydrate(queryClient, dehydratedState)
```

View File

@@ -0,0 +1,149 @@
---
id: infiniteQueryOptions
title: infiniteQueryOptions
---
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/vue-query/src/infiniteQueryOptions.ts:99](https://github.com/TanStack/query/blob/main/packages/vue-query/src/infiniteQueryOptions.ts#L99)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
`options.queryKey` is required and is the query key to generate options for.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`useInfiniteQuery`.
### Returns
[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options.
### Example
```vue
<script setup lang="ts">
import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/vue-query'
const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
const { data, isError, error, fetchNextPage } = useInfiniteQuery(projectsOptions)
</script>
```
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/vue-query/src/infiniteQueryOptions.ts:153](https://github.com/TanStack/query/blob/main/packages/vue-query/src/infiniteQueryOptions.ts#L153)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
`options.queryKey` is required and is the query key to generate options for.
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`useInfiniteQuery`, with `initialData` set.
### Returns
[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options.
### Example
```vue
<script setup lang="ts">
import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/vue-query'
const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
initialData: { pages: [], pageParams: [] },
})
// `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
// list stays visible alongside the error.
const { data, isError, error } = useInfiniteQuery(projectsOptions)
</script>
```

View File

@@ -0,0 +1,24 @@
---
id: isCancelledError
title: isCancelledError
---
```ts
function isCancelledError(value): value is CancelledError;
```
Defined in: [packages/query-core/src/retryer.ts:90](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L90)
## Parameters
### value
`any`
## Returns
`value is CancelledError`
## Deprecated
Use instanceof `CancelledError` instead.

View File

@@ -0,0 +1,40 @@
---
id: keepPreviousData
title: keepPreviousData
---
```ts
function keepPreviousData<T>(previousData): T | undefined;
```
Defined in: [packages/query-core/src/utils.ts:493](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L493)
Intended to be passed as a query's `placeholderData` option, for example
`placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
## Type Parameters
### T
`T`
## Parameters
### previousData
`T` | `undefined`
## Returns
`T` \| `undefined`
## Example
```ts
new QueryObserver(queryClient, {
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
placeholderData: keepPreviousData,
})
```

View File

@@ -0,0 +1,38 @@
---
id: matchMutation
title: matchMutation
---
```ts
function matchMutation(filters, mutation): boolean;
```
Defined in: [packages/query-core/src/utils.ts:237](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L237)
Checks whether a mutation matches the given [MutationFilters](../interfaces/MutationFilters.md).
Every filter that is specified must match; filters that are left unspecified are ignored.
If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
## Parameters
### filters
[`MutationFilters`](../interfaces/MutationFilters.md)
### mutation
[`Mutation`](../classes/Mutation.md)\<`any`, `any`\>
## Returns
`boolean`
## Example
```ts
const mutationCache = queryClient.getMutationCache()
const matchingMutations = mutationCache
.getAll()
.filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
```

View File

@@ -0,0 +1,37 @@
---
id: matchQuery
title: matchQuery
---
```ts
function matchQuery(filters, query): boolean;
```
Defined in: [packages/query-core/src/utils.ts:175](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L175)
Checks whether a query matches the given [QueryFilters](../interfaces/QueryFilters.md).
Every filter that is specified must match; filters that are left unspecified are ignored.
## Parameters
### filters
[`QueryFilters`](../interfaces/QueryFilters.md)
### query
[`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\>
## Returns
`boolean`
## Example
```ts
const queryCache = queryClient.getQueryCache()
const matchingQueries = queryCache
.getAll()
.filter((query) => matchQuery({ queryKey: ['posts'] }, query))
```

View File

@@ -0,0 +1,299 @@
---
id: mutationOptions
title: mutationOptions
---
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): WithRequired<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/vue-query/src/mutationOptions.ts:34](https://github.com/TanStack/query/blob/main/packages/vue-query/src/mutationOptions.ts#L34)
You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
`mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
`useMutationState`.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
[`WithRequired`](../type-aliases/WithRequired.md)\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The mutation options to use, identical to what you'd pass to `useMutation`, with a
required `mutationKey`.
### Returns
[`WithRequired`](../type-aliases/WithRequired.md)\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object, unchanged.
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Example
Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
```vue
<script setup lang="ts">
import { mutationOptions, useMutationState } from '@tanstack/vue-query'
import { computed } from 'vue'
const createPostOptions = mutationOptions({
mutationKey: ['posts', 'create'],
mutationFn: createPost,
})
// Call `useMutationState` once — it manages its own subscription — then derive from its result.
const creatingPosts = useMutationState({
filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
})
const isCreatingPost = computed(() => creatingPosts.value.length > 0)
</script>
```
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): () => WithRequired<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/vue-query/src/mutationOptions.ts:80](https://github.com/TanStack/query/blob/main/packages/vue-query/src/mutationOptions.ts#L80)
Same as the plain-object overload with a required `mutationKey`, but for options that close over reactive
state (`ref`s read inside the function body). Wrap them in a getter so `useMutation` and the other consumers
always read the current values instead of the ones captured when the options were created.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
() => [`WithRequired`](../type-aliases/WithRequired.md)\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
A function returning the mutation options to use, with a required `mutationKey`,
re-evaluated on demand.
### Returns
A function that returns the same options object, unchanged.
```ts
(): WithRequired<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
#### Returns
[`WithRequired`](../type-aliases/WithRequired.md)\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Example
```vue
<script setup lang="ts">
import { mutationOptions, useMutation } from '@tanstack/vue-query'
const props = defineProps<{ userId: number }>()
const createPostOptions = mutationOptions(() => ({
mutationKey: ['posts', 'create'],
// Reacts to changes on `props.userId`, unlike the plain-object overload.
mutationFn: (title: string) => createPost({ title, userId: props.userId }),
}))
const mutation = useMutation(createPostOptions)
</script>
<template>
<button @click="mutation.mutate('Hello')">Create</button>
</template>
```
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): Omit<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/vue-query/src/mutationOptions.ts:124](https://github.com/TanStack/query/blob/main/packages/vue-query/src/mutationOptions.ts#L124)
You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
`mutationKey` is required on this overload — use this when you don't need to target the mutation via a
`mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
such as `status`.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
`Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The mutation options to use, identical to what you'd pass to `useMutation`, without a
`mutationKey`.
### Returns
`Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object, unchanged.
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Remarks
See the other overload's example for looking a mutation up via `useMutationState`.
### Example
```vue
<script setup lang="ts">
import { mutationOptions, useMutation } from '@tanstack/vue-query'
const createPostOptions = mutationOptions({
mutationFn: createPost,
})
const mutation = useMutation(createPostOptions)
</script>
<template>
<button @click="mutation.mutate({ title: 'Hello' })">Create</button>
</template>
```
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): () => Omit<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/vue-query/src/mutationOptions.ts:169](https://github.com/TanStack/query/blob/main/packages/vue-query/src/mutationOptions.ts#L169)
Same as the plain-object overload without a `mutationKey`, but for options that close over reactive state
(`ref`s read inside the function body). Wrap them in a getter so `useMutation` and the other consumers
always read the current values instead of the ones captured when the options were created.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
() => `Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
A function returning the mutation options to use, without a `mutationKey`, re-evaluated on
demand.
### Returns
A function that returns the same options object, unchanged.
```ts
(): Omit<MutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
#### Returns
`Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Example
```vue
<script setup lang="ts">
import { mutationOptions, useMutation } from '@tanstack/vue-query'
const props = defineProps<{ userId: number }>()
const createPostOptions = mutationOptions(() => ({
// Reacts to changes on `props.userId`, unlike the plain-object overload.
mutationFn: (title: string) => createPost({ title, userId: props.userId }),
}))
const mutation = useMutation(createPostOptions)
</script>
<template>
<button @click="mutation.mutate('Hello')">Create</button>
</template>
```

View File

@@ -0,0 +1,32 @@
---
id: noop
title: noop
---
## Call Signature
```ts
function noop(): void;
```
Defined in: [packages/query-core/src/utils.ts:119](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L119)
A function that does nothing.
### Returns
`void`
## Call Signature
```ts
function noop(): undefined;
```
Defined in: [packages/query-core/src/utils.ts:120](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L120)
A function that does nothing.
### Returns
`undefined`

View File

@@ -0,0 +1,26 @@
---
id: partialMatchKey
title: partialMatchKey
---
```ts
function partialMatchKey(a, b): boolean;
```
Defined in: [packages/query-core/src/utils.ts:300](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L300)
Checks if key `b` partially matches with key `a`.
## Parameters
### a
readonly `unknown`[]
### b
readonly `unknown`[]
## Returns
`boolean`

View File

@@ -0,0 +1,310 @@
---
id: queryOptions
title: queryOptions
---
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/vue-query/src/queryOptions.ts:244](https://github.com/TanStack/query/blob/main/packages/vue-query/src/queryOptions.ts#L244)
You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
is the query key to generate options for.
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`DefinedInitialQueryOptions`](../type-aliases/DefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [DefinedInitialQueryOptions](../type-aliases/DefinedInitialQueryOptions.md) to use — everything you can pass to `useQuery`, with
`initialData` set.
### Returns
[`DefinedInitialQueryOptionsWithDataTag`](../type-aliases/DefinedInitialQueryOptionsWithDataTag.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[useQuery](useQuery.md) to run a query with these options.
### Example
```vue
<script setup lang="ts">
import { queryOptions, useQuery } from '@tanstack/vue-query'
const postsOptions = queryOptions({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
})
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const { data, isError, error } = useQuery(postsOptions)
</script>
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): () => DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/vue-query/src/queryOptions.ts:281](https://github.com/TanStack/query/blob/main/packages/vue-query/src/queryOptions.ts#L281)
Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always
read the current values instead of the ones captured when the options were created.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
() => [`DefinedInitialQueryOptions`](../type-aliases/DefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
A function returning the [DefinedInitialQueryOptions](../type-aliases/DefinedInitialQueryOptions.md) to use, re-evaluated on demand.
### Returns
A function that returns the same options object, typed so that `queryKey` carries the inferred data
type.
```ts
(): DefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
#### Returns
[`DefinedInitialQueryOptionsWithDataTag`](../type-aliases/DefinedInitialQueryOptionsWithDataTag.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
### See
[useQuery](useQuery.md) to run a query with these options.
### Example
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { queryOptions, useQuery } from '@tanstack/vue-query'
const postId = ref(1)
const postOptions = queryOptions(() => ({
queryKey: ['post', postId.value],
queryFn: () => fetchPost(postId.value),
initialData: { id: postId.value, title: '' },
}))
// Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
const { data } = useQuery(postOptions)
</script>
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): UndefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/vue-query/src/queryOptions.ts:326](https://github.com/TanStack/query/blob/main/packages/vue-query/src/queryOptions.ts#L326)
You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
is the query key to generate options for.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`UndefinedInitialQueryOptions`](../type-aliases/UndefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UndefinedInitialQueryOptions](../type-aliases/UndefinedInitialQueryOptions.md) to use — everything you can pass to `useQuery`.
### Returns
[`UndefinedInitialQueryOptionsWithDataTag`](../type-aliases/UndefinedInitialQueryOptionsWithDataTag.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[useQuery](useQuery.md) to run a query with these options.
### Example
A parameterized factory, so the same options object can be reused per `id`:
```vue
<script setup lang="ts">
import { queryOptions, useQuery } from '@tanstack/vue-query'
function postOptions(id: string) {
return queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
}
const { data, isPending, isError, error } = useQuery(postOptions('1'))
</script>
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): () => UndefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/vue-query/src/queryOptions.ts:392](https://github.com/TanStack/query/blob/main/packages/vue-query/src/queryOptions.ts#L392)
Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the
function body). Wrap them in a getter so the `queryKey` — and anything else derived from a `ref` — reacts
to changes, and so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current
values instead of the ones captured when the options were created.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
() => [`UndefinedInitialQueryOptions`](../type-aliases/UndefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
A function returning the [UndefinedInitialQueryOptions](../type-aliases/UndefinedInitialQueryOptions.md) to use, re-evaluated on
demand.
### Returns
A function that returns the same options object, typed so that `queryKey` carries the inferred
data type.
```ts
(): UndefinedInitialQueryOptionsWithDataTag<TQueryFnData, TError, TData, TQueryKey>;
```
#### Returns
[`UndefinedInitialQueryOptionsWithDataTag`](../type-aliases/UndefinedInitialQueryOptionsWithDataTag.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
### See
[useQuery](useQuery.md) to run a query with these options.
### Examples
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { queryOptions, useQuery, useQueryClient } from '@tanstack/vue-query'
const postId = ref(1)
const postOptions = queryOptions(() => ({
queryKey: ['post', postId.value],
queryFn: () => fetchPost(postId.value),
}))
// Pass the getter itself, not `postOptions()`, so the query keeps reacting to `postId` changes.
const { data } = useQuery(postOptions)
const queryClient = useQueryClient()
// Here, call `postOptions()` so `invalidateQueries` reads the current `queryKey` right away.
queryClient.invalidateQueries(postOptions())
</script>
```
A parameterized factory that disables the query, type safe, until `postId` is set. The whole-options getter
re-evaluates `queryFn` on every change to `postId`. `queryFn` can also be a `computed`, but never a bare
getter, since a function there is the query function itself:
```vue
<script setup lang="ts">
import { queryOptions, skipToken, useQuery } from '@tanstack/vue-query'
function postOptions(postId: number | undefined) {
return queryOptions(() => ({
queryKey: ['post', postId],
queryFn: postId != null ? () => fetchPost(postId) : skipToken,
}))
}
const props = defineProps<{ postId: number | undefined }>()
const { data, isLoading, isError, error } = useQuery(postOptions(props.postId))
</script>
```

View File

@@ -0,0 +1,41 @@
---
id: replaceEqualDeep
title: replaceEqualDeep
---
```ts
function replaceEqualDeep<T>(
a,
b,
depth?): T;
```
Defined in: [packages/query-core/src/utils.ts:339](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L339)
This function returns `a` if `b` is deeply equal.
If not, it will replace any deeply equal children of `b` with those of `a`.
This can be used for structural sharing between JSON values for example.
## Type Parameters
### T
`T`
## Parameters
### a
`unknown`
### b
`T`
### depth?
`number`
## Returns
`T`

View File

@@ -0,0 +1,45 @@
---
id: shouldThrowError
title: shouldThrowError
---
```ts
function shouldThrowError<T>(throwOnError, params): boolean;
```
Defined in: [packages/query-core/src/utils.ts:576](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L576)
Resolves a `throwOnError` option to a boolean.
If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
additional context such as the query or mutation) and its result is returned, allowing the throwing
behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
resolves to `false`).
## Type Parameters
### T
`T` *extends* (...`args`) => `boolean`
## Parameters
### throwOnError
`boolean` | `T` | `undefined`
### params
`Parameters`\<`T`\>
## Returns
`boolean`
## Example
```ts
const throwOnError =
query.state.error && typeof options.throwOnError === 'function'
? shouldThrowError(options.throwOnError, [query.state.error, query])
: options.throwOnError
```

View File

@@ -0,0 +1,386 @@
---
id: useInfiniteQuery
title: useInfiniteQuery
---
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseInfiniteQueryReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useInfiniteQuery.ts:117](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L117)
The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
individual entries — the array itself can't be a bare getter.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
`MaybeRefOrGetter`\<[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`useInfiniteQuery`, with `initialData` set.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.value.pages` and
`data.value.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
`InfiniteData<TQueryFnData>` shape.
### Remarks
Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
actions, or add conditions like `hasNextPage && !isFetching`.
### Example
```vue
<script setup lang="ts">
import { useInfiniteQuery } from '@tanstack/vue-query'
// `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
// list stays visible alongside the error.
const { data, isError, error } = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
initialData: { pages: [], pageParams: [] },
})
</script>
<template>
<span v-if="isError">Error: {{ error.message }}</span>
<ul>
<template v-for="page in data.pages" :key="page.nextId">
<li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
</template>
</ul>
</template>
```
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseInfiniteQueryReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useInfiniteQuery.ts:251](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L251)
The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
individual entries — the array itself can't be a bare getter.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
`MaybeRefOrGetter`\<[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`useInfiniteQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.value.pages` and
`data.value.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
`InfiniteData<TQueryFnData>` shape.
### Remarks
Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
actions, or add conditions like `hasNextPage && !isFetching`.
### Examples
Fetching the next page from a "Load More" button click:
```vue
<script setup lang="ts">
import { useInfiniteQuery } from '@tanstack/vue-query'
const {
data,
isPending,
isError,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
</script>
<template>
<span v-if="isPending">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<template v-else>
<ul>
<template v-for="page in data.pages" :key="page.nextId">
<li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
</template>
</ul>
<button @click="fetchNextPage()" :disabled="!hasNextPage || isFetching">
{{ isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load' }}
</button>
</template>
</template>
```
Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
sentinel element after the list:
```vue
<script setup lang="ts">
import { onUnmounted, ref, watch } from 'vue'
import { useInfiniteQuery } from '@tanstack/vue-query'
const {
data,
isPending,
isError,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
const sentinel = ref<HTMLElement>()
let observer: IntersectionObserver | undefined
watch(sentinel, (el) => {
observer?.disconnect()
if (el == null) return
observer = new IntersectionObserver(([entry]) => {
if (entry?.isIntersecting && hasNextPage.value && !isFetching.value) {
fetchNextPage()
}
})
observer.observe(el)
})
onUnmounted(() => observer?.disconnect())
</script>
<template>
<span v-if="isPending">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<template v-else>
<ul>
<template v-for="page in data.pages" :key="page.nextId">
<li v-for="project in page.projects" :key="project.id">{{ project.name }}</li>
</template>
</ul>
<div ref="sentinel">{{ isFetchingNextPage ? 'Loading more...' : '' }}</div>
</template>
</template>
```
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseInfiniteQueryReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useInfiniteQuery.ts:347](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useInfiniteQuery.ts#L347)
Fallback overload for options whose `initialData` presence isn't statically known — for example, a
`ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other
overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` for the array itself, or `ref`s and reactive getters as
individual entries — the array itself can't be a bare getter.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
`MaybeRefOrGetter`\<[`UseInfiniteQueryOptions`](../type-aliases/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
A `ref`, plain value, or reactive getter resolving to the [UseInfiniteQueryOptions](../type-aliases/UseInfiniteQueryOptions.md) to
use.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`.
### Examples
Passing a whole-options getter so `maxPages` reacts to a setting stored elsewhere, not just `queryKey`:
```vue
<script setup lang="ts">
import { useInfiniteQuery } from '@tanstack/vue-query'
const props = defineProps<{ projectId: number; maxPages: number }>()
const { data } = useInfiniteQuery(() => ({
queryKey: ['project', props.projectId, 'issues'],
queryFn: ({ pageParam }) => fetchIssues(props.projectId, pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
maxPages: props.maxPages,
}))
</script>
<template>
<template v-for="page in data?.pages" :key="page.nextId">
<li v-for="issue in page.issues" :key="issue.id">{{ issue.title }}</li>
</template>
</template>
```
A query that's disabled, type-safe, until `postId` is set — pass `skipToken` as `queryFn` instead of
setting `enabled: false`. This requires a whole-options getter: `queryFn` isn't itself reactive, so the
getter is what re-evaluates it on every change to `props.postId`:
```vue
<script setup lang="ts">
import { skipToken, useInfiniteQuery } from '@tanstack/vue-query'
const props = defineProps<{ postId: string | undefined }>()
// Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
const { data, isLoading, isError, error } = useInfiniteQuery(() => {
const postId = props.postId
return {
queryKey: ['post', postId, 'comments'],
queryFn:
postId != null
? ({ pageParam }) => fetchComments(postId, pageParam)
: skipToken,
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
}
})
</script>
<template>
<span v-if="props.postId == null">Select a post</span>
<span v-else-if="isLoading">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<ul v-else>
<template v-for="page in data.pages" :key="page.nextId">
<li v-for="comment in page.comments" :key="comment.id">{{ comment.text }}</li>
</template>
</ul>
</template>
```

View File

@@ -0,0 +1,66 @@
---
id: useIsFetching
title: useIsFetching
---
```ts
function useIsFetching(fetchingFilters, queryClient?): Ref<number>;
```
Defined in: [packages/vue-query/src/useIsFetching.ts:54](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useIsFetching.ts#L54)
The `useIsFetching` composable returns a `ref` to the `number` of the queries that your application is
loading or fetching in the background (useful for app-wide loading indicators).
`fetchingFilters` may be a plain object, `MaybeRefDeep`, or a reactive getter (`() => ({ ... })`) — pass a
getter if the filters themselves depend on other reactive state.
## Parameters
### fetchingFilters
[`UseIsFetchingFilters`](../type-aliases/UseIsFetchingFilters.md) = `{}`
The [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`Ref`\<`number`\>
A `ref` to the `number` of the queries that your application is currently loading or fetching in
the background.
## Examples
```vue
<script setup lang="ts">
import { useIsFetching } from '@tanstack/vue-query'
// How many queries matching the posts prefix are fetching?
const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
</script>
<template>
<span v-if="isFetchingPosts">Refreshing posts...</span>
</template>
```
A global loading indicator for any query fetching in the background, not just the ones on screen:
```vue
<script setup lang="ts">
import { useIsFetching } from '@tanstack/vue-query'
const isFetching = useIsFetching()
</script>
<template>
<div v-if="isFetching">Queries are fetching in the background...</div>
</template>
```

View File

@@ -0,0 +1,52 @@
---
id: useIsMutating
title: useIsMutating
---
```ts
function useIsMutating(filters, queryClient?): Ref<number>;
```
Defined in: [packages/vue-query/src/useMutationState.ts:53](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useMutationState.ts#L53)
The `useIsMutating` composable returns a `ref` to the `number` of mutations that your application currently
has `pending` (useful for app-wide loading indicators).
`filters` may be a plain object, `MaybeRefDeep`, or a reactive getter (`() => ({ ... })`) — pass a getter if
the filters themselves depend on other reactive state.
## Parameters
### filters
[`UseIsMutatingFilters`](../type-aliases/UseIsMutatingFilters.md) = `{}`
The [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`Ref`\<`number`\>
A `ref` to the `number` of the mutations that your application currently has `pending`.
## Example
```vue
<script setup lang="ts">
import { useIsMutating } from '@tanstack/vue-query'
// How many mutations matching the posts prefix are in progress?
const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
</script>
<template>
<span v-if="isMutatingPosts">Saving posts...</span>
</template>
```

View File

@@ -0,0 +1,204 @@
---
id: useMutation
title: useMutation
---
```ts
function useMutation<TData, TError, TVariables, TOnMutateResult>(options, queryClient?): UseMutationReturnType<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/vue-query/src/useMutation.ts:231](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useMutation.ts#L231)
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
`useMutation` is the composable for that.
`options` may be a plain object, a `ref`, or a reactive getter (`() => ({ ... })`) — pass a getter
if the options themselves depend on other reactive state.
## Type Parameters
### TData
`TData` = `unknown`
### TError
`TError` = `Error`
### TVariables
`TVariables` = `void`
### TOnMutateResult
`TOnMutateResult` = `unknown`
## Parameters
### options
[`UseMutationOptions`](../type-aliases/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
The [UseMutationOptions](../type-aliases/UseMutationOptions.md) to use — everything you can pass to `useMutation`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
[`UseMutationReturnType`](../type-aliases/UseMutationReturnType.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call
callbacks fire only for the latest call you've made.
## See
[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look
the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
## Examples
```vue
<script setup lang="ts">
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
function onAdd() {
addMutation.mutate('Item', {
onError: (error) => console.error('Failed to add item:', error),
})
}
</script>
<template>
<button @click="onAdd">Add</button>
</template>
```
Rendering the mutation's own state, rather than just firing it off:
```vue
<script setup lang="ts">
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
</script>
<template>
<div v-if="addMutation.isPending.value">Adding todo...</div>
<div v-else>
<div v-if="addMutation.isError.value">An error occurred: {{ addMutation.error.value.message }}</div>
<button @click="addMutation.mutate('Item')">Add</button>
</div>
</template>
```
Optimistic update via `onMutate`, rolling back on `onError`:
```vue
<script setup lang="ts">
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onMutate: async (newTodo: string) => {
await queryClient.cancelQueries({ queryKey: ['todos'] })
const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
queryClient.setQueryData<Array<string>>(['todos'], (old) => [
...(old ?? []),
newTodo,
])
// Passed to `onError` as `onMutateResult` if the mutation fails.
return { previousTodos }
},
onError: (_err, _newTodo, onMutateResult) => {
queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
</script>
<template>
<button @click="addMutation.mutate('Item')">Add</button>
</template>
```
Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
promise per call instead, so you can wait for all of them when they succeed:
```vue
<script setup lang="ts">
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
async function handleAddAll(todos: Array<string>) {
try {
await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
} catch (error) {
console.error('Failed to add todos:', error)
}
}
</script>
<template>
<button @click="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
</template>
```
If some of the mutations above can fail independently of the others, and you want to know which ones
did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
`Promise.allSettled`:
```vue
<script setup lang="ts">
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
async function handleAddAll(todos: Array<string>) {
const addResults = await Promise.allSettled(
todos.map((todo) => addMutation.mutateAsync(todo)),
)
addResults.forEach((addResult, index) => {
if (addResult.status === 'rejected') {
console.error(`Failed to add "${todos[index]}":`, addResult.reason)
}
})
}
</script>
<template>
<button @click="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
</template>
```

View File

@@ -0,0 +1,111 @@
---
id: useMutationState
title: useMutationState
---
```ts
function useMutationState<TResult, TMutation>(options, queryClient?): Readonly<Ref<TResult[]>>;
```
Defined in: [packages/vue-query/src/useMutationState.ts:196](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useMutationState.ts#L196)
`useMutationState` is a composable that gives you access to all mutations in the `MutationCache`. You can
pass `filters` ([MutationFilters](../interfaces/MutationFilters.md)) to narrow down your mutations, and `select` to transform the
mutation state.
`options` may be a plain object or a reactive getter (`() => ({ ... })`) — pass a getter if the filters
themselves depend on other reactive state.
## Type Parameters
### TResult
`TResult` = [`MutationState`](../interfaces/MutationState.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
### TMutation
`TMutation` *extends* [`Mutation`](../classes/Mutation.md)\<`any`, `any`, `any`, `any`\> = `MutationTypeFromResult`\<`TResult`\>
## Parameters
### options
The `filters` to narrow down matched mutations, and an optional `select` to transform the
mutation state.
[`MutationStateOptions`](../type-aliases/MutationStateOptions.md)\<`TResult`, `TMutation`\> | () => [`MutationStateOptions`](../type-aliases/MutationStateOptions.md)\<`TResult`, `TMutation`\>
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`Readonly`\<`Ref`\<`TResult`[]\>\>
A `ref` to an Array of whatever `select` returns for each matching mutation.
## Examples
Get all variables of all running mutations:
```vue
<script setup lang="ts">
import { useMutationState } from '@tanstack/vue-query'
const pendingVariables = useMutationState({
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
</script>
<template>{{ pendingVariables.length }} posts saving...</template>
```
Get all data for specific mutations via the `mutationKey`:
```vue
<script setup lang="ts">
import { useMutation, useMutationState } from '@tanstack/vue-query'
const mutationKey = ['posts']
// Some mutation that we want to get the state for
const mutation = useMutation({
mutationKey,
mutationFn: createPosts,
})
const savedPosts = useMutationState({
// this mutation key needs to match the mutation key of the given mutation (see above)
filters: { mutationKey, status: 'success' },
select: (mutation) => mutation.state.data,
})
</script>
<template>
<button @click="mutation.mutate(['New Post'])">
Create post ({{ savedPosts.length }} saved so far)
</button>
</template>
```
Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
last item that `useMutationState` returns to get the latest successful invocation:
```vue
<script setup lang="ts">
import { computed } from 'vue'
import { useMutationState } from '@tanstack/vue-query'
const savedPosts = useMutationState({
filters: { mutationKey: ['posts'], status: 'success' },
select: (mutation) => mutation.state.data,
})
const latestSavedPost = computed(() => savedPosts.value[savedPosts.value.length - 1])
</script>
<template>{{ latestSavedPost ? 'Saved' : 'Nothing saved yet' }}</template>
```

View File

@@ -0,0 +1,94 @@
---
id: usePrefetchInfiniteQuery
title: usePrefetchInfiniteQuery
---
```ts
function usePrefetchInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): void;
```
Defined in: [packages/vue-query/src/usePrefetchInfiniteQuery.ts:94](https://github.com/TanStack/query/blob/main/packages/vue-query/src/usePrefetchInfiniteQuery.ts#L94)
`usePrefetchInfiniteQuery` does not return anything — it fires a prefetch as a reactive side effect, useful
for kicking off a fetch ahead of the component that will actually render the data with `useInfiniteQuery`.
You can pass everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`,
though `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required
unless a default query function has been defined.
`getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
as well as pageParam information, and should return a single variable that will be passed to your query
function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left
over from a previous attempt — so it won't refetch data that's already there or already in flight. It
re-runs whenever a reactive dependency in `options` (built with `infiniteQueryOptions`, for example) changes.
Fire this during render, before a suspense boundary that wraps a component using `useInfiniteQuery`'s
`suspense()` — see the [Suspense guide](https://tanstack.com/query/latest/docs/framework/vue/guides/suspense).
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = `Error`
### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### TPageParam
`TPageParam` = `unknown`
## Parameters
### options
`MaybeRefOrGetter`\<`MaybeRefDeep`\<[`UsePrefetchInfiniteQueryOptions`](../type-aliases/UsePrefetchInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>\>
A `ref`, plain value, or reactive getter resolving to the
[UsePrefetchInfiniteQueryOptions](../type-aliases/UsePrefetchInfiniteQueryOptions.md) to use — everything you can pass to `queryClient.infiniteQuery`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`void`
`void` — nothing is returned.
## Example
```vue
<script setup lang="ts">
import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/vue-query'
import Projects from './Projects.vue'
const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
// Fire the prefetch as soon as this component runs, before `Projects` mounts and calls `useInfiniteQuery`.
usePrefetchInfiniteQuery(projectsOptions)
</script>
<template>
<Projects />
</template>
```

View File

@@ -0,0 +1,85 @@
---
id: usePrefetchQuery
title: usePrefetchQuery
---
```ts
function usePrefetchQuery<TQueryFnData, TError, TData, TQueryData, TQueryKey>(options, queryClient?): void;
```
Defined in: [packages/vue-query/src/usePrefetchQuery.ts:86](https://github.com/TanStack/query/blob/main/packages/vue-query/src/usePrefetchQuery.ts#L86)
`usePrefetchQuery` does not return anything — it fires a prefetch as a reactive side effect, useful for
kicking off a fetch ahead of the component that will actually render the data with `useQuery`. You can pass
everything to `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always
required, and `queryFn` is required unless a default query function has been defined.
The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left
over from a previous attempt — so it won't refetch data that's already there or already in flight. It
re-runs whenever a reactive dependency in `options` (built with `queryOptions`, for example) changes.
Fire this during render, before a suspense boundary that wraps a component using `useQuery`'s `suspense()`
— see the [Suspense guide](https://tanstack.com/query/latest/docs/framework/vue/guides/suspense).
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = `Error`
### TData
`TData` = `TQueryFnData`
### TQueryData
`TQueryData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
## Parameters
### options
`MaybeRefOrGetter`\<`MaybeRefDeep`\<[`UsePrefetchQueryOptions`](../type-aliases/UsePrefetchQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>\>\>
A `ref`, plain value, or reactive getter resolving to the [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to
use — everything you can pass to `queryClient.query`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`void`
`void` — nothing is returned.
## Example
```vue
<script setup lang="ts">
import { usePrefetchQuery } from '@tanstack/vue-query'
import Posts from './Posts.vue'
// Fire the prefetch as soon as this component runs, before `Posts` mounts and calls `useQuery`.
usePrefetchQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
</script>
<template>
<Posts />
</template>
```

View File

@@ -0,0 +1,156 @@
---
id: useQueries
title: useQueries
---
```ts
function useQueries<T, TCombinedResult>(__namedParameters, queryClient?): Readonly<Ref<TCombinedResult>>;
```
Defined in: [packages/vue-query/src/useQueries.ts:357](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQueries.ts#L357)
The `useQueries` composable can be used to fetch a variable number of queries.
The `queries` option accepts an array of query option objects mostly identical to `useQuery`'s. It may be a
plain array, a `ref`/reactive array (each entry tracked individually), or a getter function — pass a getter
if the array itself (its length, or which queries are in it) depends on other reactive state.
Having the same query key more than once in the array of query objects may cause some data to be shared
between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
structure.
The `combine` option can be used to combine the results of the queries into a single value. The result will
be structurally shared to be as referentially stable as possible.
`placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
previously rendered queries, because the number of queries can differ between renders.
## Type Parameters
### T
`T` *extends* `any`[]
### TCombinedResult
`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseQueryResult\<Tails\[K\<(...)\>\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseQueryResult\<T\[K\<K\>\]\> \}
## Parameters
### \_\_namedParameters
`ShallowOption` & `object`
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
## Returns
`Readonly`\<`Ref`\<`TCombinedResult`\>\>
A `ref` to the combined result. Without `combine`, this is an array with all the query results, in
the same order as the input. When `combine` is provided, this is the value returned by `combine` instead.
## Examples
```vue
<script setup lang="ts">
import { useQueries } from '@tanstack/vue-query'
const props = defineProps<{ ids: Array<number> }>()
const postQueries = useQueries({
queries: () =>
props.ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
staleTime: Infinity,
})),
})
</script>
<template>
<ul>
<li v-for="(query, index) in postQueries" :key="props.ids[index]">
<span v-if="query.isPending">Loading...</span>
<span v-else-if="query.isError">Error: {{ query.error.message }}</span>
<span v-else>{{ query.data.title }}</span>
</li>
</ul>
</template>
```
Combining results into a single value:
```vue
<script setup lang="ts">
import { useQueries } from '@tanstack/vue-query'
const props = defineProps<{ ids: Array<number> }>()
const combined = useQueries({
queries: () =>
props.ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})),
combine: (postQueries) => ({
data: postQueries.map((query) => query.data),
isPending: postQueries.some((query) => query.isPending),
isError: postQueries.some((query) => query.isError),
}),
})
</script>
<template>
<span v-if="combined.isPending">Loading...</span>
<span v-else-if="combined.isError">Error!</span>
<ul v-else>
<li v-for="post in combined.data" :key="post.id">{{ post.title }}</li>
</ul>
</template>
```
Typing `select` via [queryOptions](queryOptions.md). Note that spreading a `queryOptions` result and overriding
`select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
resolved before it reaches `useQueries`:
```vue
<script setup lang="ts">
import { queryOptions, useQueries } from '@tanstack/vue-query'
const props = defineProps<{ id: number }>()
const postOptions = (id: number) =>
queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
const [{ data: broken }] = useQueries({
queries: () => [
{
...postOptions(props.id),
// ❌ `data` is `unknown` here
select: (data) => data.title,
},
],
})
const [{ data: fixed }] = useQueries({
queries: () => [
queryOptions({
...postOptions(props.id),
// ✅ `data` is `Post`
select: (data) => data.title,
}),
],
})
</script>
<template>
<h1>{{ fixed }}</h1>
</template>
```

View File

@@ -0,0 +1,359 @@
---
id: useQuery
title: useQuery
---
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseQueryDefinedReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useQuery.ts:65](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L65)
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
reactive getters as individual entries. Other options are read once when passed as a plain value, and stay
reactive when passed as a `ref` or a `computed`.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`DefinedInitialQueryOptions`](../type-aliases/DefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [DefinedInitialQueryOptions](../type-aliases/DefinedInitialQueryOptions.md) to use — everything you can pass to `useQuery`, with
`initialData` set.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseQueryDefinedReturnType`](../type-aliases/UseQueryDefinedReturnType.md)\<`TData`, `TError`\>
The current query result, typed so that `data` is never `undefined` (`status` never resolves to
`pending` in this overload's type, since `initialData` guarantees data upfront).
### Example
```vue
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const { data, isError, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
})
</script>
<template>
<span v-if="isError">Error: {{ error.message }}</span>
<ul>
<li v-for="post in data" :key="post.id">{{ post.title }}</li>
</ul>
</template>
```
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseQueryReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useQuery.ts:206](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L206)
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
reactive getters as individual entries. Other options are read once when passed as a plain value, and stay
reactive when passed as a `ref` or a `computed`.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`UndefinedInitialQueryOptions`](../type-aliases/UndefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UndefinedInitialQueryOptions](../type-aliases/UndefinedInitialQueryOptions.md) to use — everything you can pass to `useQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\>
The current query result. `status` is `pending` if there is no cached data to display, `error` if
the last fetch attempt failed, or `success` if the query has data to display.
### Examples
A query key built from a reactive `ref` — the query refetches whenever `postId` changes:
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { useQuery } from '@tanstack/vue-query'
const postId = ref(1)
const { status, data, error } = useQuery({
queryKey: ['post', postId],
queryFn: () => fetchPost(postId.value),
})
</script>
<template>
<span v-if="status === 'pending'">Loading...</span>
<span v-else-if="status === 'error'">Error: {{ error.message }}</span>
<h1 v-else>{{ data.title }}</h1>
</template>
```
`select` derives whatever `data` a component needs from the cached value, without changing what's
actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
```vue
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
const { data, isPending, isError, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
select: (posts) => posts.length,
})
</script>
<template>
<span v-if="isPending">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<span v-else>{{ data }} posts</span>
</template>
```
A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the
loading state doesn't show while the query is disabled:
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { useQuery } from '@tanstack/vue-query'
const props = defineProps<{ postId: number | undefined }>()
const { data, isLoading, isError, error } = useQuery({
queryKey: ['post', props.postId],
queryFn: () => fetchPost(props.postId!),
enabled: () => props.postId != null,
})
</script>
<template>
<span v-if="props.postId == null">Select a post</span>
<span v-else-if="isLoading">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<h1 v-else>{{ data?.title }}</h1>
</template>
```
Seeding a detail query from an already-cached list, to skip the loading state:
```vue
<script setup lang="ts">
import { useQuery, useQueryClient } from '@tanstack/vue-query'
const props = defineProps<{ postId: number }>()
const queryClient = useQueryClient()
const { data, isError, error } = useQuery({
queryKey: ['post', props.postId],
queryFn: () => fetchPost(props.postId),
initialData: () =>
queryClient
.getQueryData<Array<Post>>(['posts'])
?.find((post) => post.id === props.postId),
})
</script>
<template>
<span v-if="isError">Error: {{ error.message }}</span>
<h1 v-else>{{ data?.title }}</h1>
</template>
```
Paginated data, keeping the previous page's data visible while the next page loads:
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { keepPreviousData, useQuery } from '@tanstack/vue-query'
const page = ref(0)
const { data, isPlaceholderData, isError, error } = useQuery({
queryKey: ['posts', page],
queryFn: () => fetchPosts(page.value),
placeholderData: keepPreviousData,
})
</script>
<template>
<span v-if="isError">Error: {{ error.message }}</span>
<template v-else>
<ul>
<li v-for="post in data" :key="post.id">{{ post.title }}</li>
</ul>
<button :disabled="isPlaceholderData" @click="page++">Next Page</button>
</template>
</template>
```
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseQueryReturnType<TData, TError>;
```
Defined in: [packages/vue-query/src/useQuery.ts:282](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L282)
Fallback overload for options whose `initialData` presence isn't statically known — for example, a
`ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other
overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
reactive getters as individual entries.
When `options` itself is a reactive getter, the whole object is re-evaluated on every change to its
dependencies, so any option inside it — not just `queryKey` and `enabled` — can change over time.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
`MaybeRefOrGetter`\<[`UseQueryOptions`](../type-aliases/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`\>\>
A `ref`, plain value, or reactive getter resolving to the [UseQueryOptions](../type-aliases/UseQueryOptions.md) to use.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
will be used.
### Returns
[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\>
The current query result, with `data` typed as possibly `undefined`.
### Examples
Passing a whole-options getter so `staleTime` reacts to a setting stored elsewhere, not just `queryKey`:
```vue
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
const props = defineProps<{ id: number; staleTime: number }>()
const { data } = useQuery(() => ({
queryKey: ['post', props.id],
queryFn: () => fetchPost(props.id),
staleTime: props.staleTime,
}))
</script>
<template>
<h1 v-if="data">{{ data.title }}</h1>
</template>
```
`skipToken` disables the query in a type-safe way, without a non-null assertion on `props.postId` —
`queryFn` is only ever called when it's defined. The whole-options getter re-evaluates `queryFn` on every
change to `props.postId`. `queryFn` can also be a `computed`, but never a bare getter, since a function
there is the query function itself. `refetch` doesn't work while `queryFn` is `skipToken` — use
`enabled: false` instead if you need to trigger the query manually:
```vue
<script setup lang="ts">
import { skipToken, useQuery } from '@tanstack/vue-query'
const props = defineProps<{ postId: number | undefined }>()
const { data, isLoading, isError, error } = useQuery(() => {
const postId = props.postId
return {
queryKey: ['post', postId],
queryFn: postId != null ? () => fetchPost(postId) : skipToken,
}
})
</script>
<template>
<span v-if="props.postId == null">Select a post</span>
<span v-else-if="isLoading">Loading...</span>
<span v-else-if="isError">Error: {{ error.message }}</span>
<h1 v-else>{{ data?.title }}</h1>
</template>
```

View File

@@ -0,0 +1,44 @@
---
id: useQueryClient
title: useQueryClient
---
```ts
function useQueryClient(id): QueryClient;
```
Defined in: [packages/vue-query/src/useQueryClient.ts:27](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQueryClient.ts#L27)
Retrieves the `QueryClient` installed by `VueQueryPlugin`, via Vue's `inject`. Must be called inside
`setup()` or another function that supports an injection context.
## Parameters
### id
`string` = `''`
The `queryClientKey` passed to `VueQueryPlugin` — only needed when multiple `QueryClient`s are
installed in the same app.
## Returns
[`QueryClient`](../classes/QueryClient.md)
## Throws
If called outside an injection context, or if no `QueryClient` was installed via `VueQueryPlugin`.
## Example
```vue
<script setup lang="ts">
import { useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
function invalidate() {
queryClient.invalidateQueries({ queryKey: ['todos'] })
}
</script>
```