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

useQuery.md

388 lines17.0 KB

1---
2id: useQuery
3title: useQuery
4redirect_from:
5 - framework/solid/reference/useQuery
6---
7​
8<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
9​
10## Overview
11​
12```ts
13function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
14function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
15```
16​
17- [`DefinedInitialDataOptions` β†’ `DefinedUseQueryResult`](#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.
18- [`UndefinedInitialDataOptions` β†’ `UseQueryResult`](#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.
19​
20See also: [Parameters](#parameters-summary) Β· [Returns](#returns-summary)
21​
22<a id="call-signature-1"></a>
23​
24## Call Signature
25​
26```ts
27function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
28```
29​
30Defined in: [packages/solid-query/src/useQuery.ts:58](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useQuery.ts#L58)
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[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
62​
63An accessor returning the [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β€” everything you can
64pass to `useQuery`, with `initialData` known to be defined.
65​
66#### queryClient?
67​
68() => [`QueryClient`](../classes/QueryClient.md)
69​
70An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
71will be used.
72​
73### Returns
74​
75[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
76​
77The current query result, as a Solid store, typed so that `status` is `success` or `error`
78(`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront).
79`status` is `error` if the query has an error from a fetch that failed after its retries or if `select`
80threw, and `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
81​
82### See
83​
84[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
85​
86### Example
87​
88```tsx
89import { For } from 'solid-js'
90import { useQuery } from '@tanstack/solid-query'
91​
92function Posts() {
93 // `postsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
94 // list stays visible alongside the error.
95 const postsQuery = useQuery(() => ({
96 queryKey: ['posts'],
97 queryFn: fetchPosts,
98 initialData: [],
99 }))
100​
101 return (
102 <div>
103 {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
104 <ul>
105 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
106 </ul>
107 </div>
108 )
110```
111​
112<a id="call-signature-2"></a>
113​
114## Call Signature
115​
116```ts
117function useQuery<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
118```
119​
120Defined in: [packages/solid-query/src/useQuery.ts:230](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useQuery.ts#L230)
121​
122Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
123The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
124​
125### Type Parameters
126​
127#### TQueryFnData
128​
129`TQueryFnData` = `unknown`
130​
131#### TError
132​
133`TError` = `Error`
134​
135#### TData
136​
137`TData` = `TQueryFnData`
138​
139#### TQueryKey
140​
141`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
142​
143### Parameters
144​
145#### options
146​
147[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
148​
149An accessor returning the [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can
150pass to `useQuery`.
151​
152#### queryClient?
153​
154() => [`QueryClient`](../classes/QueryClient.md)
155​
156An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
157will be used.
158​
159### Returns
160​
161[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
162​
163The current query result, as a Solid store. `status` is `error` if the query has an error from
164a fetch that failed after its retries or if `select` threw, `success` if the query has cached data
165(even if `select` returns `undefined`) or data from `placeholderData`, and `pending` otherwise.
166`isPending`/`isSuccess`/`isError` are derived booleans for convenience.
167​
168### See
169​
170[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
171​
172### Examples
173​
174```tsx
175import { For, Match, Switch } from 'solid-js'
176import { useQuery } from '@tanstack/solid-query'
177​
178function Posts() {
179 const postsQuery = useQuery(() => ({
180 queryKey: ['posts'],
181 queryFn: fetchPosts,
182 }))
183​
184 return (
185 <Switch>
186 <Match when={postsQuery.isPending}>Loading...</Match>
187 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
188 <Match when={postsQuery.isSuccess}>
189 <ul>
190 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
191 </ul>
192 <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
193 </Match>
194 </Switch>
195 )
197```
198​
199`select` derives whatever `data` a component needs from the cached value, without changing what's
200actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
201```tsx
202import { Match, Switch } from 'solid-js'
203import { useQuery } from '@tanstack/solid-query'
204​
205function PostCount() {
206 const postsQuery = useQuery(() => ({
207 queryKey: ['posts'],
208 queryFn: fetchPosts,
209 select: (posts) => posts.length,
210 }))
211​
212 return (
213 <Switch>
214 <Match when={postsQuery.isPending}>Loading...</Match>
215 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
216 <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
217 </Switch>
218 )
220```
221​
222A dependent query, only enabled once `postId` is set:
223```tsx
224import { Match, Switch } from 'solid-js'
225import { useQuery } from '@tanstack/solid-query'
226​
227function Post(props: { postId: number | undefined }) {
228 const postQuery = useQuery(() => ({
229 queryKey: ['post', props.postId],
230 queryFn: () => fetchPost(props.postId!),
231 enabled: props.postId != null,
232 }))
233​
234 return (
235 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
236 <Match when={props.postId == null}>Select a post</Match>
237 <Match when={postQuery.isLoading}>Loading...</Match>
238 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
239 </Switch>
240 )
242```
243​
244The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
245`enabled`. The non-null assertion is still needed β€” Solid's `props` narrowing doesn't survive into the
246`queryFn` closure the way a local `const` would β€” but `skipToken` keeps `queryFn`'s return type accurate
247without it. `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
248need to trigger the query manually:
249```tsx
250import { Match, Switch } from 'solid-js'
251import { skipToken, useQuery } from '@tanstack/solid-query'
252​
253function Post(props: { postId: number | undefined }) {
254 const postQuery = useQuery(() => ({
255 queryKey: ['post', props.postId],
256 queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
257 }))
258​
259 return (
260 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
261 <Match when={props.postId == null}>Select a post</Match>
262 <Match when={postQuery.isLoading}>Loading...</Match>
263 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
264 </Switch>
265 )
267```
268​
269Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
270over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
271fetched rather than from now:
272```tsx
273import { useQuery, useQueryClient } from '@tanstack/solid-query'
274​
275function Post(props: { postId: number }) {
276 const queryClient = useQueryClient()
277​
278 const postQuery = useQuery(() => ({
279 queryKey: ['post', props.postId],
280 queryFn: () => fetchPost(props.postId),
281 initialData: () =>
282 queryClient
283 .getQueryData<Array<Post>>(['posts'])
284 ?.find((post) => post.id === props.postId),
285 initialDataUpdatedAt: () =>
286 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
287 }))
288​
289 return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
291```
292​
293Paginated data, keeping the previous page's data visible while the next page loads:
294```tsx
295import { For, createSignal } from 'solid-js'
296import { keepPreviousData, useQuery } from '@tanstack/solid-query'
297​
298function Posts() {
299 const [page, setPage] = createSignal(0)
300​
301 const postsQuery = useQuery(() => ({
302 queryKey: ['posts', page()],
303 queryFn: () => fetchPosts(page()),
304 placeholderData: keepPreviousData,
305 }))
306​
307 return (
308 <div>
309 <ul>
310 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
311 </ul>
312 <button
313 disabled={postsQuery.isPlaceholderData}
314 onClick={() => setPage((old) => old + 1)}
315 >
316 Next Page
317 </button>
318 </div>
319 )
321```
322​
323<a id="parameters-summary"></a>
324​
325## Parameters
326​
327### options
328​
329[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
330​
331An accessor returning the [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can
332pass to `useQuery`.
333​
334<a id="options-properties"></a>
335​
336#### `options` properties
337​
338Built from [`QueryOptions`](../interfaces/QueryOptions.md#properties). See the type above for what it changes.
339​
340### queryClient?
341​
342() => [`QueryClient`](../classes/QueryClient.md)
343​
344An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
345will be used.
346​
347<a id="returns-summary"></a>
348​
349## Returns
350​
351[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
352​
353The current query result, as a Solid store. `status` is `error` if the query has an error from
354a fetch that failed after its retries or if `select` threw, `success` if the query has cached data
355(even if `select` returns `undefined`) or data from `placeholderData`, and `pending` otherwise.
356`isPending`/`isSuccess`/`isError` are derived booleans for convenience.
357​
358<a id="result-properties"></a>
359​
360### Result properties
361​
362| Property | Type | Description |
363| ------ | ------ | ------ |
364| <a id="result-property-data"></a> `data` | `TData` \| `undefined` | The last successfully resolved data for the query. |
365| <a id="result-property-dataupdatedat"></a> `dataUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"success"`. |
366| <a id="result-property-error"></a> `error` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. |
367| <a id="result-property-errorupdatecount"></a> `errorUpdateCount` | `number` | The sum of all errors. |
368| <a id="result-property-errorupdatedat"></a> `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. |
369| <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. |
370| <a id="result-property-failurereason"></a> `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. |
371| <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. |
372| <a id="result-property-isenabled"></a> `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. |
373| <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. |
374| <a id="result-property-isfetched"></a> `isFetched` | `boolean` | Will be `true` if the query has been fetched. |
375| <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. |
376| <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. |
377| <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. |
378| <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`. |
379| <a id="result-property-isloadingerror"></a> `isLoadingError` | `boolean` | Will be `true` if the query has an error and no data to display. |
380| <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`. |
381| <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. |
382| <a id="result-property-isplaceholderdata"></a> `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. |
383| <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). |
384| <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`. |
385| <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`. |
386| <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. |
387| <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. |
388| <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. |