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

createQuery.md

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