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