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

useQuery.md

412 lines13.6 KB

1---
2id: useQuery
3title: useQuery
4redirect_from:
5 - framework/vue/reference/useQuery
6---
7​
8## Overview
9​
10```ts
11function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryDefinedReturnType<TData, TError>;
12function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryReturnType<TData, TError>;
13function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: MaybeRefOrGetter<UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>>, queryClient?: QueryClient): UseQueryReturnType<TData, TError>;
14```
15​
16- [`DefinedInitialQueryOptions` β†’ `UseQueryDefinedReturnType`](#call-signature-1): This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
17- [`UndefinedInitialQueryOptions` β†’ `UseQueryReturnType`](#call-signature-2): `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`.
18- [`MaybeRefOrGetter` β†’ `UseQueryReturnType`](#call-signature-3): 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.
19​
20See also: [Parameters](#parameters-summary) Β· [Returns](#returns-summary)
21​
22<a id="call-signature-1"></a>
23​
24## Call Signature
25​
26```ts
27function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: DefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryDefinedReturnType<TData, TError>;
28```
29​
30Defined in: [packages/vue-query/src/useQuery.ts:73](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L73)
31​
32This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
33a `select` changes `TData` to include `undefined`).
34​
35`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
36(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
37reactive getters as individual entries. Other options are read once when passed as a plain value, and stay
38reactive when passed as a `ref` or a `computed`.
39​
40### Type Parameters
41​
42#### TQueryFnData
43​
44`TQueryFnData` = `unknown`
45​
46#### TError
47​
48`TError` = `Error`
49​
50#### TData
51​
52`TData` = `TQueryFnData`
53​
54#### TQueryKey
55​
56`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
57​
58### Parameters
59​
60#### options
61​
62[`DefinedInitialQueryOptions`](../type-aliases/DefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
63​
64The [DefinedInitialQueryOptions](../type-aliases/DefinedInitialQueryOptions.md) to use β€” everything you can pass to `useQuery`, with
65`initialData` set.
66​
67#### queryClient?
68​
69[`QueryClient`](../classes/QueryClient.md)
70​
71Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
72will be used.
73​
74### Returns
75​
76[`UseQueryDefinedReturnType`](../type-aliases/UseQueryDefinedReturnType.md)\<`TData`, `TError`\>
77​
78The current query result, typed so that `data` is never `undefined` (unless a `select` changes
79`TData` to include `undefined`). `status` never resolves to `pending` in this overload's type, since
80`initialData` guarantees data upfront.
81​
82### Example
83​
84```vue
85<script setup lang="ts">
86import { useQuery } from '@tanstack/vue-query'
87​
88// `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
89// so the list stays visible alongside the error.
90const { data, isError, error } = useQuery({
91 queryKey: ['posts'],
92 queryFn: fetchPosts,
93 initialData: [],
94})
95</script>
96​
97<template>
98 <span v-if="isError">Error: {{ error.message }}</span>
99 <ul>
100 <li v-for="post in data" :key="post.id">{{ post.title }}</li>
101 </ul>
102</template>
103```
104​
105<a id="call-signature-2"></a>
106​
107## Call Signature
108​
109```ts
110function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: UndefinedInitialQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryReturnType<TData, TError>;
111```
112​
113Defined in: [packages/vue-query/src/useQuery.ts:212](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L212)
114​
115`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
116(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
117reactive getters as individual entries. Other options are read once when passed as a plain value, and stay
118reactive when passed as a `ref` or a `computed`.
119​
120### Type Parameters
121​
122#### TQueryFnData
123​
124`TQueryFnData` = `unknown`
125​
126#### TError
127​
128`TError` = `Error`
129​
130#### TData
131​
132`TData` = `TQueryFnData`
133​
134#### TQueryKey
135​
136`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
137​
138### Parameters
139​
140#### options
141​
142[`UndefinedInitialQueryOptions`](../type-aliases/UndefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
143​
144The [UndefinedInitialQueryOptions](../type-aliases/UndefinedInitialQueryOptions.md) to use β€” everything you can pass to `useQuery`.
145​
146#### queryClient?
147​
148[`QueryClient`](../classes/QueryClient.md)
149​
150Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
151will be used.
152​
153### Returns
154​
155[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\>
156​
157The current query result. `status` is `pending` if there is no cached data to display, `error` if
158the last fetch attempt failed, or `success` if the query has data to display.
159​
160### Examples
161​
162A query key built from a reactive `ref` β€” the query refetches whenever `postId` changes:
163```vue
164<script setup lang="ts">
165import { ref } from 'vue'
166import { useQuery } from '@tanstack/vue-query'
167​
168const postId = ref(1)
169const { status, data, error } = useQuery({
170 queryKey: ['post', postId],
171 queryFn: () => fetchPost(postId.value),
172})
173</script>
174​
175<template>
176 <span v-if="status === 'pending'">Loading...</span>
177 <span v-else-if="status === 'error'">Error: {{ error.message }}</span>
178 <h1 v-else>{{ data.title }}</h1>
179</template>
180```
181​
182`select` derives whatever `data` a component needs from the cached value, without changing what's
183actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
184```vue
185<script setup lang="ts">
186import { useQuery } from '@tanstack/vue-query'
187​
188const { data, isPending, isError, error } = useQuery({
189 queryKey: ['posts'],
190 queryFn: fetchPosts,
191 select: (posts) => posts.length,
192})
193</script>
194​
195<template>
196 <span v-if="isPending">Loading...</span>
197 <span v-else-if="isError">Error: {{ error.message }}</span>
198 <span v-else>{{ data }} posts</span>
199</template>
200```
201​
202A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
203loading state doesn't show while the query is disabled:
204```vue
205<script setup lang="ts">
206import { ref } from 'vue'
207import { useQuery } from '@tanstack/vue-query'
208​
209const props = defineProps<{ postId: number | undefined }>()
210​
211const { data, isLoading, isError, error } = useQuery({
212 queryKey: ['post', props.postId],
213 queryFn: () => fetchPost(props.postId!),
214 enabled: () => props.postId != null,
215})
216</script>
217​
218<template>
219 <span v-if="props.postId == null">Select a post</span>
220 <span v-else-if="isLoading">Loading...</span>
221 <span v-else-if="isError">Error: {{ error.message }}</span>
222 <h1 v-else>{{ data?.title }}</h1>
223</template>
224```
225​
226Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
227over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
228fetched rather than from now:
229```vue
230<script setup lang="ts">
231import { useQuery, useQueryClient } from '@tanstack/vue-query'
232​
233const props = defineProps<{ postId: number }>()
234const queryClient = useQueryClient()
235​
236const { data, isError, error } = useQuery({
237 queryKey: ['post', props.postId],
238 queryFn: () => fetchPost(props.postId),
239 initialData: () =>
240 queryClient
241 .getQueryData<Array<Post>>(['posts'])
242 ?.find((post) => post.id === props.postId),
243 initialDataUpdatedAt: () =>
244 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
245})
246</script>
247​
248<template>
249 <span v-if="isError">Error: {{ error.message }}</span>
250 <h1 v-else>{{ data?.title }}</h1>
251</template>
252```
253​
254Paginated data, keeping the previous page's data visible while the next page loads:
255```vue
256<script setup lang="ts">
257import { ref } from 'vue'
258import { keepPreviousData, useQuery } from '@tanstack/vue-query'
259​
260const page = ref(0)
261​
262const { data, isPlaceholderData, isError, error } = useQuery({
263 queryKey: ['posts', page],
264 queryFn: () => fetchPosts(page.value),
265 placeholderData: keepPreviousData,
266})
267</script>
268​
269<template>
270 <span v-if="isError">Error: {{ error.message }}</span>
271 <template v-else>
272 <ul>
273 <li v-for="post in data" :key="post.id">{{ post.title }}</li>
274 </ul>
275 <button :disabled="isPlaceholderData" @click="page++">Next Page</button>
276 </template>
277</template>
278```
279​
280<a id="call-signature-3"></a>
281​
282## Call Signature
283​
284```ts
285function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: MaybeRefOrGetter<UseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>>, queryClient?: QueryClient): UseQueryReturnType<TData, TError>;
286```
287​
288Defined in: [packages/vue-query/src/useQuery.ts:285](https://github.com/TanStack/query/blob/main/packages/vue-query/src/useQuery.ts#L285)
289​
290Fallback overload for options whose `initialData` presence isn't statically known β€” for example, a
291`ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other
292overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
293​
294`enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter
295(`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and
296reactive getters as individual entries.
297​
298When `options` itself is a reactive getter, the whole object is re-evaluated on every change to its
299dependencies, so any option inside it β€” not just `queryKey` and `enabled` β€” can change over time.
300​
301### Type Parameters
302​
303#### TQueryFnData
304​
305`TQueryFnData` = `unknown`
306​
307#### TError
308​
309`TError` = `Error`
310​
311#### TData
312​
313`TData` = `TQueryFnData`
314​
315#### TQueryKey
316​
317`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
318​
319### Parameters
320​
321#### options
322​
323`MaybeRefOrGetter`\<[`UseQueryOptions`](../type-aliases/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`\>\>
324​
325A `ref`, plain value, or reactive getter resolving to the [UseQueryOptions](../type-aliases/UseQueryOptions.md) to use.
326​
327#### queryClient?
328​
329[`QueryClient`](../classes/QueryClient.md)
330​
331Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
332will be used.
333​
334### Returns
335​
336[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\>
337​
338The current query result, with `data` typed as possibly `undefined`.
339​
340### Examples
341​
342Passing a whole-options getter so `staleTime` reacts to a setting stored elsewhere, not just `queryKey`:
343```vue
344<script setup lang="ts">
345import { useQuery } from '@tanstack/vue-query'
346​
347const props = defineProps<{ id: number; staleTime: number }>()
348​
349const { data } = useQuery(() => ({
350 queryKey: ['post', props.id],
351 queryFn: () => fetchPost(props.id),
352 staleTime: props.staleTime,
353}))
354</script>
355​
356<template>
357 <h1 v-if="data">{{ data.title }}</h1>
358</template>
359```
360​
361`skipToken` disables the query in a type-safe way, without a non-null assertion on `props.postId` β€”
362`queryFn` is only ever called when it's defined. The whole-options getter re-evaluates `queryFn` on every
363change to `props.postId`. `queryFn` can also be a `computed`, but never a bare getter, since a function
364there is the query function itself. `refetch` doesn't work while `queryFn` is `skipToken` β€” use
365`enabled: false` instead if you need to trigger the query manually:
366```vue
367<script setup lang="ts">
368import { skipToken, useQuery } from '@tanstack/vue-query'
369​
370const props = defineProps<{ postId: number | undefined }>()
371​
372const { data, isLoading, isError, error } = useQuery(() => {
373 const postId = props.postId
374 return {
375 queryKey: ['post', postId],
376 queryFn: postId != null ? () => fetchPost(postId) : skipToken,
377 }
378})
379</script>
380​
381<template>
382 <span v-if="props.postId == null">Select a post</span>
383 <span v-else-if="isLoading">Loading...</span>
384 <span v-else-if="isError">Error: {{ error.message }}</span>
385 <h1 v-else>{{ data?.title }}</h1>
386</template>
387```
388​
389<a id="parameters-summary"></a>
390​
391## Parameters
392​
393### options
394​
395`MaybeRefOrGetter`\<[`UseQueryOptions`](../type-aliases/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`\>\>
396​
397A `ref`, plain value, or reactive getter resolving to the [UseQueryOptions](../type-aliases/UseQueryOptions.md) to use.
398​
399### queryClient?
400​
401[`QueryClient`](../classes/QueryClient.md)
402​
403Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
404will be used.
405​
406<a id="returns-summary"></a>
407​
408## Returns
409​
410[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\>
411​
412The current query result, with `data` typed as possibly `undefined`.