Open History to see the last commit
1---
2id: useQuery
3title: useQuery
4---
5β
6```tsx
7const {
8 data,
9 dataUpdatedAt,
10 error,
11 errorUpdatedAt,
12 failureCount,
13 failureReason,
14 fetchStatus,
15 isError,
16 isFetched,
17 isFetchedAfterMount,
18 isFetching,
19 isInitialLoading,
20 isLoading,
21 isLoadingError,
22 isPaused,
23 isPending,
24 isPlaceholderData,
25 isRefetchError,
26 isRefetching,
27 isStale,
28 isSuccess,
29 refetch,
30 status,
31} = useQuery(
32 () => ({
33 queryKey,
34 queryFn,
35 enabled,
36 select,
37 placeholderData,
38 deferStream,
39 reconcile,
40 gcTime,
41 networkMode,
42 initialData,
43 initialDataUpdatedAt,
44 meta,
45 queryKeyHashFn,
46 refetchInterval,
47 refetchIntervalInBackground,
48 refetchOnMount,
49 refetchOnReconnect,
50 refetchOnWindowFocus,
51 retry,
52 retryOnMount,
53 retryDelay,
54 staleTime,
55 throwOnError,
56 }),
57 () => queryClient,
58)
59```
60β
61## Usage example
62β
63Here are some examples of how to use the `useQuery` primitive in Solid Query.
64β
65### Basic
66β
67The most basic usage of `useQuery` is to create a query that fetches data from an API.
68β
69```tsx
70import { useQuery } from '@tanstack/solid-query'
71β
72function App() {
73 const todos = useQuery(() => ({
74 queryKey: 'todos',
75 queryFn: async () => {
76 const response = await fetch('/api/todos')
77 if (!response.ok) {
78 throw new Error('Failed to fetch todos')
79 }
80 return response.json()
81 },
82 }))
83β
84 return (
85 <div>
86 <Show when={todos.isError}>
87 <div>Error: {todos.error.message}</div>
88 </Show>
89 <Show when={todos.isLoading}>
90 <div>Loading...</div>
91 </Show>
92 <Show when={todos.isSuccess}>
93 <div>
94 <div>Todos:</div>
95 <ul>
96 <For each={todos.data}>{(todo) => <li>{todo.title}</li>}</For>
97 </ul>
98 </div>
99 </Show>
100 </div>
101 )
102}
103```
104β
105### Reactive Options
106β
107The reason why `useQuery` accepts a function that returns an object is to allow for reactive options. This is useful when query options depend on other values/signals that might change over time. Solid Query can track the passed function in a reactive scope and re-run it whenever the dependencies change.
108β
109```tsx
110import { useQuery } from '@tanstack/solid-query'
111β
112function App() {
113 const [filter, setFilter] = createSignal('all')
114β
115 const todos = useQuery(() => ({
116 queryKey: ['todos', filter()],
117 queryFn: async () => {
118 const response = await fetch(`/api/todos?filter=${filter()}`)
119 if (!response.ok) {
120 throw new Error('Failed to fetch todos')
121 }
122 return response.json()
123 },
124 }))
125β
126 return (
127 <div>
128 <div>
129 <button onClick={() => setFilter('all')}>All</button>
130 <button onClick={() => setFilter('active')}>Active</button>
131 <button onClick={() => setFilter('completed')}>Completed</button>
132 </div>
133 <Show when={todos.isError}>
134 <div>Error: {todos.error.message}</div>
135 </Show>
136 <Show when={todos.isLoading}>
137 <div>Loading...</div>
138 </Show>
139 <Show when={todos.isSuccess}>
140 <div>
141 <div>Todos:</div>
142 <ul>
143 <For each={todos.data}>{(todo) => <li>{todo.title}</li>}</For>
144 </ul>
145 </div>
146 </Show>
147 </div>
148 )
149}
150```
151β
152### Usage with `Suspense`
153β
154`useQuery` supports triggering SolidJS `Suspense` and `ErrorBoundary` components when the query is in a pending or error state. This allows you to easily handle loading and error states in your components.
155β
156```tsx
157import { useQuery } from '@tanstack/solid-query'
158β
159function App() {
160 const todos = useQuery(() => ({
161 queryKey: 'todos',
162 queryFn: async () => {
163 const response = await fetch('/api/todos')
164 if (!response.ok) {
165 throw new Error('Failed to fetch todos')
166 }
167 return response.json()
168 },
169 throwOnError: true,
170 }))
171β
172 return (
173 <ErrorBoundary fallback={<div>Error: {todos.error.message}</div>}>
174 <Suspense fallback={<div>Loading...</div>}>
175 <div>
176 <div>Todos:</div>
177 <ul>
178 <For each={todos.data}>{(todo) => <li>{todo.title}</li>}</For>
179 </ul>
180 </div>
181 </Suspense>
182 </ErrorBoundary>
183 )
184}
185```
186β
187## `useQuery` Parameters
188β
189- ### Query Options - `Accessor<QueryOptions>`
190 - ##### `queryKey: unknown[]`
191 - **Required**
192 - The query key to use for this query.
193 - The query key will be hashed into a stable hash. See [Query Keys](../../guides/query-keys.md) for more information.
194 - The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
195 - ##### `queryFn: (context: QueryFunctionContext) => Promise<TData>`
196 - **Required, but only if no default query function has been defined** See [Default Query Function](../../guides/default-query-function.md) for more information.
197 - The function that the query will use to request data.
198 - Receives a [QueryFunctionContext](../../guides/query-functions.md#queryfunctioncontext)
199 - Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`.
200 - ##### `enabled: boolean`
201 - Set this to `false` to disable this query from automatically running.
202 - Can be used for [Dependent Queries](../../guides/dependent-queries.md) for more information.
203 - ##### `select: (data: TData) => unknown`
204 - Optional
205 - This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache.
206 - The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. To optimize, wrap the function in `useCallback`.
207 - ##### `placeholderData: TData | (previousValue: TData | undefined; previousQuery: Query | undefined,) => TData`
208 - Optional
209 - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state.
210 - `placeholderData` is **not persisted** to the cache
211 - If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance.
212 - ##### `deferStream: boolean`
213 - Optional
214 - Defaults to `false`
215 - Only applicable while rendering queries on the server with streaming.
216 - Set `deferStream` to `true` to wait for the query to resolve on the server before flushing the stream.
217 - This can be useful to avoid sending a loading state to the client before the query has resolved.
218 - ##### `reconcile: false | string | ((oldData: TData | undefined, newData: TData) => TData)`
219 - Optional
220 - Defaults to `false`
221 - Set this to a string to enable reconciliation between query results based on the string key.
222 - Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom reconciliation logic.
223 - ##### `gcTime: number | Infinity`
224 - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR
225 - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used.
226 - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider).
227 - If set to `Infinity`, will disable garbage collection
228 - ##### `networkMode: 'online' | 'always' | 'offlineFirst'`
229 - optional
230 - defaults to `'online'`
231 - see [Network Mode](../../guides/network-mode.md) for more information.
232 - ##### `initialData: TData | () => TData`
233 - Optional
234 - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet)
235 - If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData
236 - Initial data is considered stale by default unless a `staleTime` has been set.
237 - `initialData` **is persisted** to the cache
238 - ##### `initialDataUpdatedAt: number | (() => number | undefined)`
239 - Optional
240 - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
241 - ##### `meta: Record<string, unknown>`
242 - Optional
243 - If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`.
244 - ##### `queryKeyHashFn: (queryKey: QueryKey) => string`
245 - Optional
246 - If specified, this function is used to hash the `queryKey` to a string.
247 - ##### `refetchInterval: number | false | ((query: Query) => number | false | undefined)`
248 - Optional
249 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
250 - If set to a function, the function will be executed with the query to compute a frequency
251 - ##### `refetchIntervalInBackground: boolean`
252 - Optional
253 - If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background
254 - ##### `refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")`
255 - Optional
256 - Defaults to `true`
257 - If set to `true`, the query will refetch on mount if the data is stale.
258 - If set to `false`, the query will not refetch on mount.
259 - If set to `"always"`, the query will always refetch on mount.
260 - If set to a function, the function will be executed with the query to compute the value
261 - ##### `refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")`
262 - Optional
263 - Defaults to `true`
264 - If set to `true`, the query will refetch on window focus if the data is stale.
265 - If set to `false`, the query will not refetch on window focus.
266 - If set to `"always"`, the query will always refetch on window focus.
267 - If set to a function, the function will be executed with the query to compute the value
268 - ##### `refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")`
269 - Optional
270 - Defaults to `true`
271 - If set to `true`, the query will refetch on reconnect if the data is stale.
272 - If set to `false`, the query will not refetch on reconnect.
273 - If set to `"always"`, the query will always refetch on reconnect.
274 - If set to a function, the function will be executed with the query to compute the value
275 - ##### `retry: boolean | number | (failureCount: number, error: TError) => boolean`
276 - If `false`, failed queries will not retry by default.
277 - If `true`, failed queries will retry infinitely.
278 - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number.
279 - defaults to `3` on the client and `0` on the server
280 - ##### `retryOnMount: boolean`
281 - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`.
282 - ##### `retryDelay: number | (retryAttempt: number, error: TError) => number`
283 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
284 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
285 - A function like `attempt => attempt * 1000` applies linear backoff.
286 - ##### `staleTime: number | Infinity`
287 - Optional
288 - Defaults to `0`
289 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
290 - If set to `Infinity`, the data will never be considered stale
291 - ##### `throwOnError: undefined | boolean | (error: TError, query: Query) => boolean`
292 - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary
293 - Set this to `false` to disable `suspense`'s default behavior of throwing errors to the error boundary.
294 - If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`)
295β
296- ### Query Client - `Accessor<QueryClient>`
297 - Optional
298 - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
299β
300## `useQuery` Return Value - `Store<QueryResult<TData, TError>>`
301β
302`useQuery` returns a SolidJS store with the following properties:
303β
304- ##### `status: QueryStatus`
305 - Will be:
306 - `pending` if there's no cached data and no query attempt was finished yet.
307 - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
308 - `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization.
309- ##### `isPending: boolean`
310 - A derived boolean from the `status` variable above, provided for convenience.
311- ##### `isSuccess: boolean`
312 - A derived boolean from the `status` variable above, provided for convenience.
313- ##### `isError: boolean`
314 - A derived boolean from the `status` variable above, provided for convenience.
315- ##### `isLoadingError: boolean`
316 - Will be `true` if the query failed while fetching for the first time.
317- ##### `isRefetchError: boolean`
318 - Will be `true` if the query failed while refetching.
319- ##### `data: Resource<TData>`
320 - Defaults to `undefined`.
321 - The last successfully resolved data for the query.
322 - **Important**: The `data` property is a SolidJS resource. This means that if the data is accessed underneath a `<Suspense>` component,
323 it will trigger the Suspense boundary if the data is not available yet.
324- ##### `dataUpdatedAt: number`
325 - The timestamp for when the query most recently returned the `status` as `"success"`.
326- ##### `error: null | TError`
327 - Defaults to `null`
328 - The error object for the query, if an error was thrown.
329- ##### `errorUpdatedAt: number`
330 - The timestamp for when the query most recently returned the `status` as `"error"`.
331- ##### `isStale: boolean`
332 - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`.
333- ##### `isPlaceholderData: boolean`
334 - Will be `true` if the data shown is the placeholder data.
335- ##### `isFetched: boolean`
336 - Will be `true` if the query has been fetched.
337- ##### `isFetchedAfterMount: boolean`
338 - Will be `true` if the query has been fetched after the component mounted.
339 - This property can be used to not show any previously cached data.
340- ##### `fetchStatus: FetchStatus`
341 - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches.
342 - `paused`: The query wanted to fetch, but has been `paused`.
343 - `idle`: The query is not fetching.
344 - see [Network Mode](../../guides/network-mode.md) for more information.
345- ##### `isFetching: boolean`
346 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
347- ##### `isPaused: boolean`
348 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
349- ##### `isRefetching: boolean`
350 - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`
351 - Is the same as `isFetching && !isPending`
352- ##### `isLoading: boolean`
353 - Is `true` whenever the first fetch for a query is in-flight
354 - Is the same as `isFetching && isPending`
355- ##### `isInitialLoading: boolean`
356 - **deprecated**
357 - An alias for `isLoading`, will be removed in the next major version.
358- ##### `failureCount: number`
359 - The failure count for the query.
360 - Incremented every time the query fails.
361 - Reset to `0` when the query succeeds.
362- ##### `failureReason: null | TError`
363 - The failure reason for the query retry.
364 - Reset to `null` when the query succeeds.
365- ##### `errorUpdateCount: number`
366 - The sum of all errors.
367- ##### `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
368 - A function to manually refetch the query.
369 - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option
370 - `cancelRefetch?: boolean`
371 - Defaults to `true`
372 - Per default, a currently running request will be cancelled before a new request is made
373 - When set to `false`, no refetch will be made if there is already a request running.