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

useQuery.md

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