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

createQuery.md

308 lines9.7 KB

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