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

createQuery.md

476 lines32.1 KB

1---
2id: createQuery
3title: createQuery
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8## Overview
9​
10```ts
11function createQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): DefinedCreateQueryResult<TData, TError>;
12function createQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): CreateQueryResult<TData, TError>;
13function createQuery<TQueryFnData, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): CreateQueryResult<TData, TError>;
14```
15​
16- [`DefinedInitialDataOptions` β†’ `DefinedCreateQueryResult`](#call-signature-1): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
17- [`UndefinedInitialDataOptions` β†’ `CreateQueryResult`](#call-signature-2): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
18- [`CreateQueryOptions` β†’ `CreateQueryResult`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an object typed as [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) rather than an 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 createQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): DefinedCreateQueryResult<TData, TError>;
28```
29​
30Defined in: [packages/svelte-query/src/createQuery.ts:55](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L55)
31​
32Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
33The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
34​
35This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
36`undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
37if `select` throws on its first call.
38​
39### Type Parameters
40​
41#### TQueryFnData
42​
43`TQueryFnData` = `unknown`
44​
45#### TError
46​
47`TError` = `Error`
48​
49#### TData
50​
51`TData` = `TQueryFnData`
52​
53#### TQueryKey
54​
55`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
56​
57### Parameters
58​
59#### options
60​
61[`Accessor`](../type-aliases/Accessor.md)\<[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
62​
63The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β€” everything you can pass to `createQuery`,
64with `initialData` known to be defined, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
65​
66#### queryClient?
67​
68[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
69​
70Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
71be used.
72​
73### Returns
74​
75[`DefinedCreateQueryResult`](../type-aliases/DefinedCreateQueryResult.md)\<`TData`, `TError`\>
76​
77The current query result, typed so that `status` is `success` or `error` (`status` never
78resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is
79`error` if the query has an error from a fetch that failed after its retries or if `select` threw, and
80`success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
81​
82### See
83​
84[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
85​
86### Example
87​
88```svelte
89<script lang="ts">
90 import { createQuery } from '@tanstack/svelte-query'
91​
92 // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
93 // so the list stays visible alongside the error.
94 const query = createQuery(() => ({
95 queryKey: ['posts'],
96 queryFn: fetchPosts,
97 initialData: [],
98 }))
99</script>
100​
101{#if query.isError}
102 <span>Error: {query.error.message}</span>
103{/if}
104<ul>
105 {#each query.data as post (post.id)}
106 <li>{post.title}</li>
107 {/each}
108</ul>
109```
110​
111<a id="call-signature-2"></a>
112​
113## Call Signature
114​
115```ts
116function createQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): CreateQueryResult<TData, TError>;
117```
118​
119Defined in: [packages/svelte-query/src/createQuery.ts:127](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L127)
120​
121Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
122The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
123​
124### Type Parameters
125​
126#### TQueryFnData
127​
128`TQueryFnData` = `unknown`
129​
130#### TError
131​
132`TError` = `Error`
133​
134#### TData
135​
136`TData` = `TQueryFnData`
137​
138#### TQueryKey
139​
140`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
141​
142### Parameters
143​
144#### options
145​
146[`Accessor`](../type-aliases/Accessor.md)\<[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
147​
148The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can pass to `createQuery`,
149wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
150​
151#### queryClient?
152​
153[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
154​
155Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
156be used.
157​
158### Returns
159​
160[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
161​
162The current query result. `status` is `error` if the query has an error from a fetch that failed
163after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
164`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
165are derived booleans for convenience.
166​
167### See
168​
169[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
170​
171### Examples
172​
173```svelte
174<script lang="ts">
175 import { createQuery } from '@tanstack/svelte-query'
176​
177 const query = createQuery(() => ({
178 queryKey: ['posts'],
179 queryFn: fetchPosts,
180 }))
181</script>
182​
183{#if query.status === 'pending'}
184 Loading...
185{:else if query.status === 'error'}
186 <span>Error: {query.error.message}</span>
187{:else}
188 <ul>
189 {#each query.data as post (post.id)}
190 <li>{post.title}</li>
191 {/each}
192 </ul>
193{/if}
194```
195​
196The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
197```svelte
198<script lang="ts">
199 import { createQuery } from '@tanstack/svelte-query'
200​
201 const query = createQuery(() => ({
202 queryKey: ['posts'],
203 queryFn: fetchPosts,
204 }))
205</script>
206​
207{#if query.isPending}
208 Loading...
209{:else if query.isError}
210 <span>Error: {query.error.message}</span>
211{:else}
212 <ul>
213 {#each query.data as post (post.id)}
214 <li>{post.title}</li>
215 {/each}
216 </ul>
217{/if}
218```
219​
220<a id="call-signature-3"></a>
221​
222## Call Signature
223​
224```ts
225function createQuery<TQueryFnData, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: Accessor<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>>, queryClient?: Accessor<QueryClient>): CreateQueryResult<TData, TError>;
226```
227​
228Defined in: [packages/svelte-query/src/createQuery.ts:253](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L253)
229​
230Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an
231object typed as [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) rather than an object literal. Prefer one of the other
232overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
233​
234### Type Parameters
235​
236#### TQueryFnData
237​
238`TQueryFnData`
239​
240#### TError
241​
242`TError` = `Error`
243​
244#### TData
245​
246`TData` = `TQueryFnData`
247​
248#### TQueryKey
249​
250`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
251​
252### Parameters
253​
254#### options
255​
256[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
257​
258The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use β€” everything you can pass to `createQuery`, wrapped
259in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
260​
261#### queryClient?
262​
263[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
264​
265Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
266be used.
267​
268### Returns
269​
270[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
271​
272The current query result. `status` is `error` if the query has an error from a fetch that failed
273after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
274`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
275are derived booleans for convenience.
276​
277### See
278​
279[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
280​
281### Examples
282​
283`select` derives whatever `data` a component needs from the cached value, without changing what's
284actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
285```svelte
286<script lang="ts">
287 import { createQuery } from '@tanstack/svelte-query'
288​
289 const query = createQuery(() => ({
290 queryKey: ['posts'],
291 queryFn: fetchPosts,
292 select: (posts) => posts.length,
293 }))
294</script>
295​
296{#if query.isPending}
297 Loading...
298{:else if query.isError}
299 <span>Error: {query.error.message}</span>
300{:else}
301 <span>{query.data} posts</span>
302{/if}
303```
304​
305A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
306loading state doesn't show while the query is disabled:
307```svelte
308<script lang="ts">
309 import { createQuery } from '@tanstack/svelte-query'
310​
311 let { postId }: { postId: number | undefined } = $props()
312​
313 const query = createQuery(() => ({
314 queryKey: ['post', postId],
315 queryFn: () => fetchPost(postId!),
316 enabled: postId != null,
317 }))
318</script>
319​
320{#if postId == null}
321 Select a post
322{:else if query.isLoading}
323 Loading...
324{:else if query.isError}
325 <span>Error: {query.error.message}</span>
326{:else}
327 <h1>{query.data?.title}</h1>
328{/if}
329```
330​
331Seeding a detail query from an already-cached list, to skip the loading state:
332```svelte
333<script lang="ts">
334 import { createQuery, useQueryClient } from '@tanstack/svelte-query'
335​
336 let { postId }: { postId: number } = $props()
337​
338 const queryClient = useQueryClient()
339​
340 const query = createQuery(() => ({
341 queryKey: ['post', postId],
342 queryFn: () => fetchPost(postId),
343 initialData: () =>
344 queryClient
345 .getQueryData<Array<Post>>(['posts'])
346 ?.find((post) => post.id === postId),
347 }))
348</script>
349​
350{#if query.isError}
351 <span>Error: {query.error.message}</span>
352{/if}
353<h1>{query.data?.title}</h1>
354```
355​
356Paginated data, keeping the previous page's data visible while the next page loads:
357```svelte
358<script lang="ts">
359 import { createQuery, keepPreviousData } from '@tanstack/svelte-query'
360​
361 let page = $state(0)
362​
363 const query = createQuery(() => ({
364 queryKey: ['posts', page],
365 queryFn: () => fetchPosts(page),
366 placeholderData: keepPreviousData,
367 }))
368</script>
369​
370{#if query.isError}
371 <span>Error: {query.error.message}</span>
372{/if}
373<ul>
374 {#each query.data ?? [] as post (post.id)}
375 <li>{post.title}</li>
376 {/each}
377</ul>
378<button disabled={query.isPlaceholderData} onclick={() => page++}>
379 Next Page
380</button>
381```
382​
383<a id="parameters-summary"></a>
384​
385## Parameters
386​
387### options
388​
389[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
390​
391The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use β€” everything you can pass to `createQuery`, wrapped
392in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
393​
394<a id="options-properties"></a>
395​
396#### `options` properties
397​
398| Property | Type | Default value | Description |
399| ------ | ------ | ------ | ------ |
400| <a id="options-property-enabled"></a> `enabled?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean`) | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. |
401| <a id="options-property-gctime"></a> `gcTime?` | `number` | `undefined` | The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay β€” see `timeoutManager.setTimeoutProvider` for a workaround. |
402| <a id="options-property-initialdata"></a> `initialData?` | `TQueryData` \| (() => `TQueryData` \| `undefined`) | `undefined` | If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet). If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initial data. Initial data is considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the cache. |
403| <a id="options-property-initialdataupdatedat"></a> `initialDataUpdatedAt?` | `number` \| (() => `number` \| `undefined`) | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. |
404| <a id="options-property-maxpages"></a> `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. |
405| <a id="options-property-meta"></a> `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. |
406| <a id="options-property-networkmode"></a> `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
407| <a id="options-property-notifyonchangeprops"></a> `notifyOnChangeProps?` | \| `"all"` \| ( \| `"error"` \| `"fetchStatus"` \| `"status"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"`)[] \| (() => \| `"all"` \| ( \| `"error"` \| `"fetchStatus"` \| `"status"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"`)[] \| `undefined`) | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. |
408| <a id="options-property-persister"></a> `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. |
409| <a id="options-property-placeholderdata"></a> `placeholderData?` | \| `NonFunctionGuard`\<`TQueryData`\> \| ((`previousData`: `NonFunctionGuard`\<`TQueryData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryData`\>, `TError`, `NonFunctionGuard`\<`TQueryData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryData`\> \| `undefined`) | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. |
410| <a id="options-property-queryfn"></a> `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| ((`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>) | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. |
411| <a id="options-property-queryhash"></a> `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. |
412| <a id="options-property-querykey"></a> `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). |
413| <a id="options-property-querykeyhashfn"></a> `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. |
414| <a id="options-property-refetchinterval"></a> `refetchInterval?` | \| `number` \| `false` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `false` \| `undefined`) | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency |
415| <a id="options-property-refetchintervalinbackground"></a> `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. |
416| <a id="options-property-refetchonmount"></a> `refetchOnMount?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value |
417| <a id="options-property-refetchonreconnect"></a> `refetchOnReconnect?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `undefined` | If set to `true`, the query will refetch on reconnect if the data is stale. If set to `false`, the query will not refetch on reconnect. If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. |
418| <a id="options-property-refetchonwindowfocus"></a> `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"`) | `true` | If set to `true`, the query will refetch on window focus if the data is stale. If set to `false`, the query will not refetch on window focus. If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). If set to a function, the function will be executed with the latest data and query to compute the value. |
419| <a id="options-property-retry"></a> `retry?` | \| `number` \| `false` \| `true` \| ((`failureCount`: `number`, `error`: `TError`) => `boolean`) | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. |
420| <a id="options-property-retrydelay"></a> `retryDelay?` | `number` \| ((`failureCount`: `number`, `error`: `TError`) => `number`) | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. A function like `attempt => attempt * 1000` applies linear backoff. Defaults to a function that applies exponential backoff, capped at 30 seconds. |
421| <a id="options-property-retryonmount"></a> `retryOnMount?` | \| `false` \| `true` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean`) | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. |
422| <a id="options-property-select"></a> `select?` | (`data`: `TQueryData`) => `TData` | `undefined` | This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. To optimize, memoize the function so its reference stays stable across calls. |
423| <a id="options-property-staletime"></a> `staleTime?` | \| `number` \| `"static"` \| ((`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `"static"`) | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. |
424| <a id="options-property-structuralsharing"></a> `structuralSharing?` | `boolean` \| ((`oldData`: `unknown`, `newData`: `unknown`) => `unknown`) | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. |
425| <a id="options-property-suspense"></a> `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. |
426| <a id="options-property-throwonerror"></a> `throwOnError?` | \| `false` \| `true` \| ((`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean`) | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). |
427​
428### queryClient?
429​
430[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
431​
432Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
433be used.
434​
435<a id="returns-summary"></a>
436​
437## Returns
438​
439[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
440​
441The current query result. `status` is `error` if the query has an error from a fetch that failed
442after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
443`undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
444are derived booleans for convenience.
445​
446<a id="result-properties"></a>
447​
448### Result properties
449​
450| Property | Type | Description |
451| ------ | ------ | ------ |
452| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
453| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
454| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
455| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
456| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
457| <a id="result-property-failurecount"></a> `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. |
458| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
459| <a id="result-property-fetchstatus"></a> `fetchStatus` | `"idle"` \| `"fetching"` \| `"paused"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
460| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
461| <a id="result-property-iserror"></a> `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. |
462| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
463| <a id="result-property-isfetchedaftermount"></a> `isFetchedAfterMount` | `boolean` | Will be `true` if the query has been fetched after the component mounted. - This property can be used to not show any previously cached data. |
464| <a id="result-property-isfetching"></a> `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. |
465| <a id="result-property-isinitialloading"></a> ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. |
466| <a id="result-property-isloading"></a> `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. |
467| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query has an error and no data to display. |
468| <a id="result-property-ispaused"></a> `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. |
469| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `true` if the query has no cached data, no data from `placeholderData` and no error. |
470| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
471| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). |
472| <a id="result-property-isrefetching"></a> `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. |
473| <a id="result-property-isstale"></a> `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. |
474| <a id="result-property-issuccess"></a> `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has cached data or data from `placeholderData`, and no error. |
475| <a id="result-property-refetch"></a> `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. |
476| <a id="result-property-status"></a> `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - Will be: - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. |