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

createQuery.md

306 lines9.5 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 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 )
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 )
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 )
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 )
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 )
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>
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 )
306```