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

useQuery.md

375 lines16.9 KB

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