Open History to see the last commit
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 )
100}
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 )
183}
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 )
206}
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 )
228}
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 )
253}
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>
277}
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 )
307}
308```