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

createQuery.md

375 lines16.7 KB

1---
2id: createQuery
3title: createQuery
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} = createQuery(
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,
59```
60​
61## Usage example
62​
63Here are some examples of how to use the `createQuery` primitive in Solid Query.
64​
65### Basic
66​
67The most basic usage of `createQuery` is to create a query that fetches data from an API.
68​
69```tsx
70import { createQuery } from '@tanstack/solid-query'
71​
72function App() {
73 const todos = createQuery(() => ({
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 )
103```
104​
105### Reactive Options
106​
107The reason why `createQuery` 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 { createQuery } from '@tanstack/solid-query'
111​
112function App() {
113 const [filter, setFilter] = createSignal('all')
114​
115 const todos = createQuery(() => ({
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 )
150```
151​
152### Usage with `Suspense`
153​
154`createQuery` 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 { createQuery } from '@tanstack/solid-query'
158​
159function App() {
160 const todos = createQuery(() => ({
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 )
185```
186​
187## `createQuery` Parameters
188​
189- ### Query Options - `Accessor<QueryOptions>`
190​
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) 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) for more information.
198 - The function that the query will use to request data.
199 - Receives a [QueryFunctionContext](../../guides/query-functions#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).
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. See [more](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value).
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) 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`
282 - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`.
283 - ##### `retryDelay: number | (retryAttempt: number, error: TError) => number`
284 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
285 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
286 - A function like `attempt => attempt * 1000` applies linear backoff.
287 - ##### `staleTime: number | Infinity`
288 - Optional
289 - Defaults to `0`
290 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
291 - If set to `Infinity`, the data will never be considered stale
292 - ##### `throwOnError: undefined | boolean | (error: TError, query: Query) => boolean`
293 - Defaults to the global query config's `throwOnError` value, which is `undefined`
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## `createQuery` Return Value - `Store<QueryResult<TData, TError>>`
303​
304`createQuery` 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) 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.