Open History to see the last commit
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 )
109}
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 )
196}
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 )
219}
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 )
241}
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 )
266}
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>
290}
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 )
320}
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. |