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

createQuery.md

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