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

useQuery.md

301 lines9.0 KB

1---
2id: useQuery
3title: useQuery
4redirect_from:
5 - framework/solid/reference/useQuery
6---
7​
8## Call Signature
9​
10```ts
11function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
12```
13​
14Defined in: [packages/solid-query/src/useQuery.ts:185](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useQuery.ts#L185)
15​
16Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
17The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
18​
19### Type Parameters
20​
21#### TQueryFnData
22​
23`TQueryFnData` = `unknown`
24​
25#### TError
26​
27`TError` = `Error`
28​
29#### TData
30​
31`TData` = `TQueryFnData`
32​
33#### TQueryKey
34​
35`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
36​
37### Parameters
38​
39#### options
40​
41[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
42​
43An accessor returning the [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can
44pass to `useQuery`.
45​
46#### queryClient?
47​
48() => [`QueryClient`](../classes/QueryClient.md)
49​
50An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
51will be used.
52​
53### Returns
54​
55[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
56​
57The current query result, as a Solid store. `status` is `pending` if there is no cached data to
58display, `error` if the last fetch attempt failed, or `success` if the query has data to display.
59`isPending`/`isSuccess`/`isError` are derived booleans for convenience.
60​
61### See
62​
63[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
64​
65### Examples
66​
67```tsx
68import { For, Match, Switch } from 'solid-js'
69import { useQuery } from '@tanstack/solid-query'
70​
71function Posts() {
72 const postsQuery = useQuery(() => ({
73 queryKey: ['posts'],
74 queryFn: fetchPosts,
75 }))
76​
77 return (
78 <Switch>
79 <Match when={postsQuery.isPending}>Loading...</Match>
80 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
81 <Match when={postsQuery.isSuccess}>
82 <ul>
83 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
84 </ul>
85 <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
86 </Match>
87 </Switch>
88 )
90```
91​
92`select` derives whatever `data` a component needs from the cached value, without changing what's
93actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
94```tsx
95import { Match, Switch } from 'solid-js'
96import { useQuery } from '@tanstack/solid-query'
97​
98function PostCount() {
99 const postsQuery = useQuery(() => ({
100 queryKey: ['posts'],
101 queryFn: fetchPosts,
102 select: (posts) => posts.length,
103 }))
104​
105 return (
106 <Switch>
107 <Match when={postsQuery.isPending}>Loading...</Match>
108 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
109 <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
110 </Switch>
111 )
113```
114​
115A dependent query, only enabled once `postId` is set:
116```tsx
117import { Match, Switch } from 'solid-js'
118import { useQuery } from '@tanstack/solid-query'
119​
120function Post(props: { postId: number | undefined }) {
121 const postQuery = useQuery(() => ({
122 queryKey: ['post', props.postId],
123 queryFn: () => fetchPost(props.postId!),
124 enabled: props.postId != null,
125 }))
126​
127 return (
128 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
129 <Match when={props.postId == null}>Select a post</Match>
130 <Match when={postQuery.isLoading}>Loading...</Match>
131 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
132 </Switch>
133 )
135```
136​
137The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
138`enabled`. The non-null assertion is still needed β€” Solid's `props` narrowing doesn't survive into the
139`queryFn` closure the way a local `const` would β€” but `skipToken` keeps `queryFn`'s return type accurate
140without it. `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
141need to trigger the query manually:
142```tsx
143import { Match, Switch } from 'solid-js'
144import { skipToken, useQuery } from '@tanstack/solid-query'
145​
146function Post(props: { postId: number | undefined }) {
147 const postQuery = useQuery(() => ({
148 queryKey: ['post', props.postId],
149 queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
150 }))
151​
152 return (
153 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
154 <Match when={props.postId == null}>Select a post</Match>
155 <Match when={postQuery.isLoading}>Loading...</Match>
156 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
157 </Switch>
158 )
160```
161​
162Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
163over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
164fetched rather than from now:
165```tsx
166import { useQuery, useQueryClient } from '@tanstack/solid-query'
167​
168function Post(props: { postId: number }) {
169 const queryClient = useQueryClient()
170​
171 const postQuery = useQuery(() => ({
172 queryKey: ['post', props.postId],
173 queryFn: () => fetchPost(props.postId),
174 initialData: () =>
175 queryClient
176 .getQueryData<Array<Post>>(['posts'])
177 ?.find((post) => post.id === props.postId),
178 initialDataUpdatedAt: () =>
179 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
180 }))
181​
182 return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
184```
185​
186Paginated data, keeping the previous page's data visible while the next page loads:
187```tsx
188import { For, createSignal } from 'solid-js'
189import { keepPreviousData, useQuery } from '@tanstack/solid-query'
190​
191function Posts() {
192 const [page, setPage] = createSignal(0)
193​
194 const postsQuery = useQuery(() => ({
195 queryKey: ['posts', page()],
196 queryFn: () => fetchPosts(page()),
197 placeholderData: keepPreviousData,
198 }))
199​
200 return (
201 <div>
202 <ul>
203 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
204 </ul>
205 <button
206 disabled={postsQuery.isPlaceholderData}
207 onClick={() => setPage((old) => old + 1)}
208 >
209 Next Page
210 </button>
211 </div>
212 )
214```
215​
216## Call Signature
217​
218```ts
219function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
220```
221​
222Defined in: [packages/solid-query/src/useQuery.ts:237](https://github.com/TanStack/query/blob/main/packages/solid-query/src/useQuery.ts#L237)
223​
224Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
225The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
226​
227This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
228a `select` changes `TData` to include `undefined`).
229​
230### Type Parameters
231​
232#### TQueryFnData
233​
234`TQueryFnData` = `unknown`
235​
236#### TError
237​
238`TError` = `Error`
239​
240#### TData
241​
242`TData` = `TQueryFnData`
243​
244#### TQueryKey
245​
246`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
247​
248### Parameters
249​
250#### options
251​
252[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
253​
254An accessor returning the [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β€” everything you can
255pass to `useQuery`, with `initialData` set.
256​
257#### queryClient?
258​
259() => [`QueryClient`](../classes/QueryClient.md)
260​
261An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
262will be used.
263​
264### Returns
265​
266[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
267​
268The current query result, as a Solid store, typed so that `status` is `success` β€” or `error` if a
269fetch attempt fails while keeping the existing data (`status` never resolves to `pending` in this overload's
270type, since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for
271convenience.
272​
273### See
274​
275[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
276​
277### Example
278​
279```tsx
280import { For } from 'solid-js'
281import { useQuery } from '@tanstack/solid-query'
282​
283function Posts() {
284 // `postsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
285 // list stays visible alongside the error.
286 const postsQuery = useQuery(() => ({
287 queryKey: ['posts'],
288 queryFn: fetchPosts,
289 initialData: [],
290 }))
291​
292 return (
293 <div>
294 {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
295 <ul>
296 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
297 </ul>
298 </div>
299 )
301```