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

useQuery.md

248 lines12.3 KB

1---
2id: useQuery
3title: useQuery
4---
5​
6```js
7const {
8 data,
9 dataUpdatedAt,
10 error,
11 errorUpdatedAt,
12 failureCount,
13 isError,
14 isFetched,
15 isFetchedAfterMount,
16 isFetching,
17 isIdle,
18 isLoading,
19 isLoadingError,
20 isPlaceholderData,
21 isPreviousData,
22 isRefetchError,
23 isRefetching,
24 isStale,
25 isSuccess,
26 refetch,
27 remove,
28 status,
29} = useQuery(queryKey, queryFn?, {
30 cacheTime,
31 enabled,
32 initialData,
33 initialDataUpdatedAt
34 isDataEqual,
35 keepPreviousData,
36 meta,
37 notifyOnChangeProps,
38 notifyOnChangePropsExclusions,
39 onError,
40 onSettled,
41 onSuccess,
42 placeholderData,
43 queryKeyHashFn,
44 refetchInterval,
45 refetchIntervalInBackground,
46 refetchOnMount,
47 refetchOnReconnect,
48 refetchOnWindowFocus,
49 retry,
50 retryOnMount,
51 retryDelay,
52 select,
53 staleTime,
54 structuralSharing,
55 suspense,
56 useErrorBoundary,
57})
58​
59// or using the object syntax
60​
61const result = useQuery({
62 queryKey,
63 queryFn,
64 enabled,
65})
66```
67​
68**Options**
69​
70- `queryKey: string | unknown[]`
71 - **Required**
72 - The query key to use for this query.
73 - The query key will be hashed into a stable hash. See [Query Keys](../guides/query-keys) for more information.
74 - The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
75- `queryFn: (context: QueryFunctionContext) => Promise<TData>`
76 - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function) for more information.
77 - The function that the query will use to request data.
78 - Receives a `QueryFunctionContext` object with the following variables:
79 - `queryKey: EnsuredQueryKey`: the queryKey, guaranteed to be an Array
80 - Must return a promise that will either resolve data or throw an error.
81- `enabled: boolean`
82 - Set this to `false` to disable this query from automatically running.
83 - Can be used for [Dependent Queries](../guides/dependent-queries).
84- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
85 - If `false`, failed queries will not retry by default.
86 - If `true`, failed queries will retry infinitely.
87 - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number.
88- `retryOnMount: boolean`
89 - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`.
90- `retryDelay: number | (retryAttempt: number, error: TError) => number`
91 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
92 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
93 - A function like `attempt => attempt * 1000` applies linear backoff.
94- `staleTime: number | Infinity`
95 - Optional
96 - Defaults to `0`
97 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
98 - If set to `Infinity`, the data will never be considered stale
99- `cacheTime: number | Infinity`
100 - Defaults to `5 * 60 * 1000` (5 minutes)
101 - 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 cache times are specified, the longest one will be used.
102 - If set to `Infinity`, will disable garbage collection
103- `queryKeyHashFn: (queryKey: QueryKey) => string`
104 - Optional
105 - If specified, this function is used to hash the `queryKey` to a string.
106- `refetchInterval: number | false | ((data: TData | undefined, query: Query) => number | false)`
107 - Optional
108 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
109 - If set to a function, the function will be executed with the latest data and query to compute a frequency
110- `refetchIntervalInBackground: boolean`
111 - Optional
112 - 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
113- `refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")`
114 - Optional
115 - Defaults to `true`
116 - If set to `true`, the query will refetch on mount if the data is stale.
117 - If set to `false`, the query will not refetch on mount.
118 - If set to `"always"`, the query will always refetch on mount.
119 - If set to a function, the function will be executed with the query to compute the value
120- `refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")`
121 - Optional
122 - Defaults to `true`
123 - If set to `true`, the query will refetch on window focus if the data is stale.
124 - If set to `false`, the query will not refetch on window focus.
125 - If set to `"always"`, the query will always refetch on window focus.
126 - If set to a function, the function will be executed with the query to compute the value
127- `refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")`
128 - Optional
129 - Defaults to `true`
130 - If set to `true`, the query will refetch on reconnect if the data is stale.
131 - If set to `false`, the query will not refetch on reconnect.
132 - If set to `"always"`, the query will always refetch on reconnect.
133 - If set to a function, the function will be executed with the query to compute the value
134- `notifyOnChangeProps: string[] | "tracked"`
135 - Optional
136 - If set, the component will only re-render if any of the listed properties change.
137 - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change.
138 - If set to `"tracked"`, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
139- `notifyOnChangePropsExclusions: string[]`
140 - Optional
141 - If set, the component will not re-render if any of the listed properties change.
142 - If set to `['isStale']` for example, the component will not re-render when the `isStale` property changes.
143- `onSuccess: (data: TData) => void`
144 - Optional
145 - This function will fire any time the query successfully fetches new data or the cache is updated via `setQueryData`.
146- `onError: (error: TError) => void`
147 - Optional
148 - This function will fire if the query encounters an error and will be passed the error.
149- `onSettled: (data?: TData, error?: TError) => void`
150 - Optional
151 - This function will fire any time the query is either successfully fetched or errors and be passed either the data or error
152- `select: (data: TData) => unknown`
153 - Optional
154 - This option can be used to transform or select a part of the data returned by the query function.
155- `suspense: boolean`
156 - Optional
157 - Set this to `true` to enable suspense mode.
158 - When `true`, `useQuery` will suspend when `status === 'loading'`
159 - When `true`, `useQuery` will throw runtime errors when `status === 'error'`
160- `initialData: TData | () => TData`
161 - Optional
162 - 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)
163 - 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
164 - Initial data is considered stale by default unless a `staleTime` has been set.
165 - `initialData` **is persisted** to the cache
166- `initialDataUpdatedAt: number | (() => number | undefined)`
167 - Optional
168 - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
169- `placeholderData: TData | () => TData`
170 - Optional
171 - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided.
172 - `placeholderData` is **not persisted** to the cache
173- `keepPreviousData: boolean`
174 - Optional
175 - Defaults to `false`
176 - If set, any previous `data` will be kept when fetching new data because the query key changed.
177- `structuralSharing: boolean`
178 - Optional
179 - Defaults to `true`
180 - If set to `false`, structural sharing between query results will be disabled.
181- `useErrorBoundary: undefined | boolean | (error: TError, query: Query) => boolean`
182 - Defaults to the global query config's `useErrorBoundary` value, which is `undefined`
183 - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary
184 - Set this to `false` to disable `suspense`'s default behavior of throwing errors to the error boundary.
185 - 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`)
186- `meta: Record<string, unknown>`
187 - Optional
188 - 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`.
189​
190**Returns**
191​
192- `status: String`
193 - Will be:
194 - `idle` if the query is idle. This only happens if a query is initialized with `enabled: false` and no initial data is available.
195 - `loading` if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg `isFetching === true`
196 - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
197 - `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.
198- `isIdle: boolean`
199 - A derived boolean from the `status` variable above, provided for convenience.
200- `isLoading: boolean`
201 - A derived boolean from the `status` variable above, provided for convenience.
202- `isSuccess: boolean`
203 - A derived boolean from the `status` variable above, provided for convenience.
204- `isError: boolean`
205 - A derived boolean from the `status` variable above, provided for convenience.
206- `isLoadingError: boolean`
207 - Will be `true` if the query failed while fetching for the first time.
208- `isRefetchError: boolean`
209 - Will be `true` if the query failed while refetching.
210- `data: TData`
211 - Defaults to `undefined`.
212 - The last successfully resolved data for the query.
213- `dataUpdatedAt: number`
214 - The timestamp for when the query most recently returned the `status` as `"success"`.
215- `error: null | TError`
216 - Defaults to `null`
217 - The error object for the query, if an error was thrown.
218- `errorUpdatedAt: number`
219 - The timestamp for when the query most recently returned the `status` as `"error"`.
220- `isStale: boolean`
221 - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`.
222- `isPlaceholderData: boolean`
223 - Will be `true` if the data shown is the placeholder data.
224- `isPreviousData: boolean`
225 - Will be `true` when `keepPreviousData` is set and data from the previous query is returned.
226- `isFetched: boolean`
227 - Will be `true` if the query has been fetched.
228- `isFetchedAfterMount: boolean`
229 - Will be `true` if the query has been fetched after the component mounted.
230 - This property can be used to not show any previously cached data.
231- `isFetching: boolean`
232 - Is `true` whenever a request is in-flight, which includes initial `loading` as well as background refetches.
233 - Will be `true` if the query is currently fetching, including background fetching.
234- `isRefetching: boolean`
235 - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `loading`
236 - Is the same as `isFetching && !isLoading`
237- `failureCount: number`
238 - The failure count for the query.
239 - Incremented every time the query fails.
240 - Reset to `0` when the query succeeds.
241- `errorUpdateCount: number`
242 - The sum of all errors.
243- `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
244 - A function to manually refetch the query.
245 - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option
246 - If `cancelRefetch` is `true`, then the current request will be cancelled before a new request is made
247- `remove: () => void`
248 - A function to remove the query from the cache.