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

createQuery.md

304 lines9.2 KB

1---
2id: createQuery
3title: createQuery
4---
5​
6```ts
7const createQuery: {
8<TQueryFnData, TError, TData, TQueryKey> (options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
9<TQueryFnData, TError, TData, TQueryKey> (options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
10} = useQuery;
11```
12​
13Defined in: [packages/solid-query/src/index.ts:57](https://github.com/TanStack/query/blob/main/packages/solid-query/src/index.ts#L57)
14​
15## Call Signature
16​
17```ts
18<TQueryFnData, TError, TData, TQueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
19```
20​
21Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
22The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
23​
24### Type Parameters
25​
26#### TQueryFnData
27​
28`TQueryFnData` = `unknown`
29​
30#### TError
31​
32`TError` = `Error`
33​
34#### TData
35​
36`TData` = `TQueryFnData`
37​
38#### TQueryKey
39​
40`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
41​
42### Parameters
43​
44#### options
45​
46[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
47​
48An accessor returning the [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β€” everything you can
49pass to `useQuery`.
50​
51#### queryClient?
52​
53() => [`QueryClient`](../classes/QueryClient.md)
54​
55An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
56will be used.
57​
58### Returns
59​
60[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
61​
62The current query result, as a Solid store. `status` is `pending` if there is no cached data to
63display, `error` if the last fetch attempt failed, or `success` if the query has data to display.
64`isPending`/`isSuccess`/`isError` are derived booleans for convenience.
65​
66### See
67​
68[queryOptions](../functions/queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
69​
70### Examples
71​
72```tsx
73import { For, Match, Switch } from 'solid-js'
74import { useQuery } from '@tanstack/solid-query'
75​
76function Posts() {
77 const postsQuery = useQuery(() => ({
78 queryKey: ['posts'],
79 queryFn: fetchPosts,
80 }))
81​
82 return (
83 <Switch>
84 <Match when={postsQuery.isPending}>Loading...</Match>
85 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
86 <Match when={postsQuery.isSuccess}>
87 <ul>
88 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
89 </ul>
90 <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
91 </Match>
92 </Switch>
93 )
95```
96​
97`select` derives whatever `data` a component needs from the cached value, without changing what's
98actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
99```tsx
100import { Match, Switch } from 'solid-js'
101import { useQuery } from '@tanstack/solid-query'
102​
103function PostCount() {
104 const postsQuery = useQuery(() => ({
105 queryKey: ['posts'],
106 queryFn: fetchPosts,
107 select: (posts) => posts.length,
108 }))
109​
110 return (
111 <Switch>
112 <Match when={postsQuery.isPending}>Loading...</Match>
113 <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
114 <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
115 </Switch>
116 )
118```
119​
120A dependent query, only enabled once `postId` is set:
121```tsx
122import { Match, Switch } from 'solid-js'
123import { useQuery } from '@tanstack/solid-query'
124​
125function Post(props: { postId: number | undefined }) {
126 const postQuery = useQuery(() => ({
127 queryKey: ['post', props.postId],
128 queryFn: () => fetchPost(props.postId!),
129 enabled: props.postId != null,
130 }))
131​
132 return (
133 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
134 <Match when={props.postId == null}>Select a post</Match>
135 <Match when={postQuery.isLoading}>Loading...</Match>
136 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
137 </Switch>
138 )
140```
141​
142The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
143`enabled`. The non-null assertion is still needed β€” Solid's `props` narrowing doesn't survive into the
144`queryFn` closure the way a local `const` would β€” but `skipToken` keeps `queryFn`'s return type accurate
145without it. `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
146need to trigger the query manually:
147```tsx
148import { Match, Switch } from 'solid-js'
149import { skipToken, useQuery } from '@tanstack/solid-query'
150​
151function Post(props: { postId: number | undefined }) {
152 const postQuery = useQuery(() => ({
153 queryKey: ['post', props.postId],
154 queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
155 }))
156​
157 return (
158 <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
159 <Match when={props.postId == null}>Select a post</Match>
160 <Match when={postQuery.isLoading}>Loading...</Match>
161 <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
162 </Switch>
163 )
165```
166​
167Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
168over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
169fetched rather than from now:
170```tsx
171import { useQuery, useQueryClient } from '@tanstack/solid-query'
172​
173function Post(props: { postId: number }) {
174 const queryClient = useQueryClient()
175​
176 const postQuery = useQuery(() => ({
177 queryKey: ['post', props.postId],
178 queryFn: () => fetchPost(props.postId),
179 initialData: () =>
180 queryClient
181 .getQueryData<Array<Post>>(['posts'])
182 ?.find((post) => post.id === props.postId),
183 initialDataUpdatedAt: () =>
184 queryClient.getQueryState(['posts'])?.dataUpdatedAt,
185 }))
186​
187 return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
189```
190​
191Paginated data, keeping the previous page's data visible while the next page loads:
192```tsx
193import { For, createSignal } from 'solid-js'
194import { keepPreviousData, useQuery } from '@tanstack/solid-query'
195​
196function Posts() {
197 const [page, setPage] = createSignal(0)
198​
199 const postsQuery = useQuery(() => ({
200 queryKey: ['posts', page()],
201 queryFn: () => fetchPosts(page()),
202 placeholderData: keepPreviousData,
203 }))
204​
205 return (
206 <div>
207 <ul>
208 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
209 </ul>
210 <button
211 disabled={postsQuery.isPlaceholderData}
212 onClick={() => setPage((old) => old + 1)}
213 >
214 Next Page
215 </button>
216 </div>
217 )
219```
220​
221## Call Signature
222​
223```ts
224<TQueryFnData, TError, TData, TQueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
225```
226​
227Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
228The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
229​
230This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
231a `select` changes `TData` to include `undefined`).
232​
233### Type Parameters
234​
235#### TQueryFnData
236​
237`TQueryFnData` = `unknown`
238​
239#### TError
240​
241`TError` = `Error`
242​
243#### TData
244​
245`TData` = `TQueryFnData`
246​
247#### TQueryKey
248​
249`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
250​
251### Parameters
252​
253#### options
254​
255[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
256​
257An accessor returning the [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β€” everything you can
258pass to `useQuery`, with `initialData` set.
259​
260#### queryClient?
261​
262() => [`QueryClient`](../classes/QueryClient.md)
263​
264An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
265will be used.
266​
267### Returns
268​
269[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
270​
271The current query result, as a Solid store, typed so that `status` is `success` β€” or `error` if a
272fetch attempt fails while keeping the existing data (`status` never resolves to `pending` in this overload's
273type, since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for
274convenience.
275​
276### See
277​
278[queryOptions](../functions/queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
279​
280### Example
281​
282```tsx
283import { For } from 'solid-js'
284import { useQuery } from '@tanstack/solid-query'
285​
286function Posts() {
287 // `postsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
288 // list stays visible alongside the error.
289 const postsQuery = useQuery(() => ({
290 queryKey: ['posts'],
291 queryFn: fetchPosts,
292 initialData: [],
293 }))
294​
295 return (
296 <div>
297 {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
298 <ul>
299 <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
300 </ul>
301 </div>
302 )
304```