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

useQuery.md

384 lines16.1 KB

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