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