Open History to see the last commit
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 )
94}
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 )
117}
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 )
139}
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 )
164}
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>
188}
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 )
218}
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 )
303}
304```