Open History to see the last commit
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:53](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L53)
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 never
36`undefined` (unless a `select` changes `TData` to include `undefined`).
37β
38### Type Parameters
39β
40#### TQueryFnData
41β
42`TQueryFnData` = `unknown`
43β
44#### TError
45β
46`TError` = `Error`
47β
48#### TData
49β
50`TData` = `TQueryFnData`
51β
52#### TQueryKey
53β
54`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
55β
56### Parameters
57β
58#### options
59β
60[`Accessor`](../type-aliases/Accessor.md)\<[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
61β
62The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β everything you can pass to `createQuery`,
63with `initialData` known to be defined, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
64β
65#### queryClient?
66β
67[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
68β
69Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
70be used.
71β
72### Returns
73β
74[`DefinedCreateQueryResult`](../type-aliases/DefinedCreateQueryResult.md)\<`TData`, `TError`\>
75β
76The current query result, typed so that `status` is `success` β or `error` if a fetch attempt
77fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
78since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
79β
80### See
81β
82[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
83β
84### Example
85β
86```svelte
87<script lang="ts">
88 import { createQuery } from '@tanstack/svelte-query'
89β
90 // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
91 // so the list stays visible alongside the error.
92 const query = createQuery(() => ({
93 queryKey: ['posts'],
94 queryFn: fetchPosts,
95 initialData: [],
96 }))
97</script>
98β
99{#if query.isError}
100 <span>Error: {query.error.message}</span>
101{/if}
102<ul>
103 {#each query.data as post (post.id)}
104 <li>{post.title}</li>
105 {/each}
106</ul>
107```
108β
109<a id="call-signature-2"></a>
110β
111## Call Signature
112β
113```ts
114function 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>;
115```
116β
117Defined in: [packages/svelte-query/src/createQuery.ts:124](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L124)
118β
119Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
120The query runs when the options call for it β `enabled: false` skips the initial fetch.
121β
122### Type Parameters
123β
124#### TQueryFnData
125β
126`TQueryFnData` = `unknown`
127β
128#### TError
129β
130`TError` = `Error`
131β
132#### TData
133β
134`TData` = `TQueryFnData`
135β
136#### TQueryKey
137β
138`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
139β
140### Parameters
141β
142#### options
143β
144[`Accessor`](../type-aliases/Accessor.md)\<[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
145β
146The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β everything you can pass to `createQuery`,
147wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
148β
149#### queryClient?
150β
151[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
152β
153Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
154be used.
155β
156### Returns
157β
158[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
159β
160The current query result. `status` is `pending` if there is no cached data to display, `error` if
161the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
162are derived booleans for convenience.
163β
164### See
165β
166[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
167β
168### Examples
169β
170```svelte
171<script lang="ts">
172 import { createQuery } from '@tanstack/svelte-query'
173β
174 const query = createQuery(() => ({
175 queryKey: ['posts'],
176 queryFn: fetchPosts,
177 }))
178</script>
179β
180{#if query.status === 'pending'}
181 Loading...
182{:else if query.status === 'error'}
183 <span>Error: {query.error.message}</span>
184{:else}
185 <ul>
186 {#each query.data as post (post.id)}
187 <li>{post.title}</li>
188 {/each}
189 </ul>
190{/if}
191```
192β
193The same query, checking `isPending`/`isError` instead of `status` β pick whichever reads better to you:
194```svelte
195<script lang="ts">
196 import { createQuery } from '@tanstack/svelte-query'
197β
198 const query = createQuery(() => ({
199 queryKey: ['posts'],
200 queryFn: fetchPosts,
201 }))
202</script>
203β
204{#if query.isPending}
205 Loading...
206{:else if query.isError}
207 <span>Error: {query.error.message}</span>
208{:else}
209 <ul>
210 {#each query.data as post (post.id)}
211 <li>{post.title}</li>
212 {/each}
213 </ul>
214{/if}
215```
216β
217<a id="call-signature-3"></a>
218β
219## Call Signature
220β
221```ts
222function 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>;
223```
224β
225Defined in: [packages/svelte-query/src/createQuery.ts:249](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L249)
226β
227Fallback overload for options whose `initialData` presence isn't statically known β for example, an
228object typed as [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) rather than an object literal. Prefer one of the other
229overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
230β
231### Type Parameters
232β
233#### TQueryFnData
234β
235`TQueryFnData`
236β
237#### TError
238β
239`TError` = `Error`
240β
241#### TData
242β
243`TData` = `TQueryFnData`
244β
245#### TQueryKey
246β
247`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
248β
249### Parameters
250β
251#### options
252β
253[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
254β
255The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use β everything you can pass to `createQuery`, wrapped
256in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
257β
258#### queryClient?
259β
260[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
261β
262Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
263be used.
264β
265### Returns
266β
267[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
268β
269The current query result. `status` is `pending` if there is no cached data to display, `error` if
270the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
271are derived booleans for convenience.
272β
273### See
274β
275[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
276β
277### Examples
278β
279`select` derives whatever `data` a component needs from the cached value, without changing what's
280actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
281```svelte
282<script lang="ts">
283 import { createQuery } from '@tanstack/svelte-query'
284β
285 const query = createQuery(() => ({
286 queryKey: ['posts'],
287 queryFn: fetchPosts,
288 select: (posts) => posts.length,
289 }))
290</script>
291β
292{#if query.isPending}
293 Loading...
294{:else if query.isError}
295 <span>Error: {query.error.message}</span>
296{:else}
297 <span>{query.data} posts</span>
298{/if}
299```
300β
301A dependent query, only enabled once `postId` is set β use `isLoading`, not `isPending`, so the
302loading state doesn't show while the query is disabled:
303```svelte
304<script lang="ts">
305 import { createQuery } from '@tanstack/svelte-query'
306β
307 let { postId }: { postId: number | undefined } = $props()
308β
309 const query = createQuery(() => ({
310 queryKey: ['post', postId],
311 queryFn: () => fetchPost(postId!),
312 enabled: postId != null,
313 }))
314</script>
315β
316{#if postId == null}
317 Select a post
318{:else if query.isLoading}
319 Loading...
320{:else if query.isError}
321 <span>Error: {query.error.message}</span>
322{:else}
323 <h1>{query.data?.title}</h1>
324{/if}
325```
326β
327Seeding a detail query from an already-cached list, to skip the loading state:
328```svelte
329<script lang="ts">
330 import { createQuery, useQueryClient } from '@tanstack/svelte-query'
331β
332 let { postId }: { postId: number } = $props()
333β
334 const queryClient = useQueryClient()
335β
336 const query = createQuery(() => ({
337 queryKey: ['post', postId],
338 queryFn: () => fetchPost(postId),
339 initialData: () =>
340 queryClient
341 .getQueryData<Array<Post>>(['posts'])
342 ?.find((post) => post.id === postId),
343 }))
344</script>
345β
346{#if query.isError}
347 <span>Error: {query.error.message}</span>
348{/if}
349<h1>{query.data?.title}</h1>
350```
351β
352Paginated data, keeping the previous page's data visible while the next page loads:
353```svelte
354<script lang="ts">
355 import { createQuery, keepPreviousData } from '@tanstack/svelte-query'
356β
357 let page = $state(0)
358β
359 const query = createQuery(() => ({
360 queryKey: ['posts', page],
361 queryFn: () => fetchPosts(page),
362 placeholderData: keepPreviousData,
363 }))
364</script>
365β
366{#if query.isError}
367 <span>Error: {query.error.message}</span>
368{/if}
369<ul>
370 {#each query.data ?? [] as post (post.id)}
371 <li>{post.title}</li>
372 {/each}
373</ul>
374<button disabled={query.isPlaceholderData} onclick={() => page++}>
375 Next Page
376</button>
377```
378β
379<a id="parameters-summary"></a>
380β
381## Parameters
382β
383### options
384β
385[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
386β
387The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use β everything you can pass to `createQuery`, wrapped
388in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
389β
390<a id="options-properties"></a>
391β
392#### `options` properties
393β
394| Property | Type | Default value | Description |
395| ------ | ------ | ------ | ------ |
396| <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. |
397| <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. |
398| <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. |
399| <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. |
400| <a id="options-property-maxpages"></a> `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. |
401| <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. |
402| <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. |
403| <a id="options-property-notifyonchangeprops"></a> `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| (() => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `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. |
404| <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. |
405| <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. |
406| <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`. |
407| <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. |
408| <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`). |
409| <a id="options-property-querykeyhashfn"></a> `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. |
410| <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 |
411| <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. |
412| <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 |
413| <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'`. |
414| <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. |
415| <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. |
416| <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. |
417| <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. |
418| <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. |
419| <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`. |
420| <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. |
421| <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'`. |
422| <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`). |
423β
424### queryClient?
425β
426[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
427β
428Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
429be used.
430β
431<a id="returns-summary"></a>
432β
433## Returns
434β
435[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
436β
437The current query result. `status` is `pending` if there is no cached data to display, `error` if
438the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
439are derived booleans for convenience.
440β
441<a id="result-properties"></a>
442β
443### Result properties
444β
445| Property | Type | Description |
446| ------ | ------ | ------ |
447| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
448| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
449| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
450| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
451| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
452| <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. |
453| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
454| <a id="result-property-fetchstatus"></a> `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | 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. |
455| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
456| <a id="result-property-iserror"></a> `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. |
457| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
458| <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. |
459| <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. |
460| <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. |
461| <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`. |
462| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. |
463| <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`. |
464| <a id="result-property-ispending"></a> `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. |
465| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
466| <a id="result-property-isrefetcherror"></a> `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. |
467| <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`. |
468| <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`. |
469| <a id="result-property-issuccess"></a> `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. |
470| <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. |
471| <a id="result-property-status"></a> `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - Will be: - `pending` if there's no cached data and no query attempt was finished yet. - `error` if the query attempt resulted in an error. - `success` if the query has received a response with no errors and is ready to display its data. |