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

useQuery.md

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