Open History to see the last commit
1import { QueryObserver } from '@tanstack/query-core'
2import { createMemo } from 'solid-js'
3import { useBaseQuery } from './useBaseQuery'
4import type { DefaultError, QueryKey } from '@tanstack/query-core'
5import type { Accessor } from 'solid-js'
6import type { QueryClient } from './QueryClient'
7import type {
8 DefinedInitialDataOptions,
9 UndefinedInitialDataOptions,
10} from './queryOptions'
11import type {
12 DefinedUseQueryResult,
13 UseQueryOptions,
14 UseQueryResult,
15} from './types'
16β
17/**
18 * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
19 * The query runs when the options call for it β `enabled: false` skips the initial fetch.
20 *
21 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
22 * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
23 * if `select` throws on its first call.
24 * @param options - An accessor returning the {@link DefinedInitialDataOptions} to use β everything you can
25 * pass to `useQuery`, with `initialData` known to be defined.
26 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
27 * will be used.
28 * @returns The current query result, as a Solid store, typed so that `status` is `success` or `error`
29 * (`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront).
30 * `status` is `error` if the query has an error from a fetch that failed after its retries or if `select`
31 * threw, and `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
32 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
33 * @example
34 * ```tsx
35 * import { For } from 'solid-js'
36 * import { useQuery } from '@tanstack/solid-query'
37 *
38 * function Posts() {
39 * // `postsQuery.data` is never `undefined`, thanks to `initialData` β even if a refetch fails, so the
40 * // list stays visible alongside the error.
41 * const postsQuery = useQuery(() => ({
42 * queryKey: ['posts'],
43 * queryFn: fetchPosts,
44 * initialData: [],
45 * }))
46 *
47 * return (
48 * <div>
49 * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
50 * <ul>
51 * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
52 * </ul>
53 * </div>
54 * )
55 * }
56 * ```
57 */
58export function useQuery<
59 TQueryFnData = unknown,
60 TError = DefaultError,
61 TData = TQueryFnData,
62 TQueryKey extends QueryKey = QueryKey,
63>(
64 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
65 queryClient?: () => QueryClient,
66): DefinedUseQueryResult<TData, TError>
67β
68/**
69 * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
70 * The query runs when the options call for it β `enabled: false` skips the initial fetch.
71 * @param options - An accessor returning the {@link UndefinedInitialDataOptions} to use β everything you can
72 * pass to `useQuery`.
73 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
74 * will be used.
75 * @returns The current query result, as a Solid store. `status` is `error` if the query has an error from
76 * a fetch that failed after its retries or if `select` threw, `success` if the query has cached data
77 * (even if `select` returns `undefined`) or data from `placeholderData`, and `pending` otherwise.
78 * `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
79 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
80 * @example
81 * ```tsx
82 * import { For, Match, Switch } from 'solid-js'
83 * import { useQuery } from '@tanstack/solid-query'
84 *
85 * function Posts() {
86 * const postsQuery = useQuery(() => ({
87 * queryKey: ['posts'],
88 * queryFn: fetchPosts,
89 * }))
90 *
91 * return (
92 * <Switch>
93 * <Match when={postsQuery.isPending}>Loading...</Match>
94 * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
95 * <Match when={postsQuery.isSuccess}>
96 * <ul>
97 * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
98 * </ul>
99 * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
100 * </Match>
101 * </Switch>
102 * )
103 * }
104 * ```
105 * @example
106 * `select` derives whatever `data` a component needs from the cached value, without changing what's
107 * actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
108 * ```tsx
109 * import { Match, Switch } from 'solid-js'
110 * import { useQuery } from '@tanstack/solid-query'
111 *
112 * function PostCount() {
113 * const postsQuery = useQuery(() => ({
114 * queryKey: ['posts'],
115 * queryFn: fetchPosts,
116 * select: (posts) => posts.length,
117 * }))
118 *
119 * return (
120 * <Switch>
121 * <Match when={postsQuery.isPending}>Loading...</Match>
122 * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
123 * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
124 * </Switch>
125 * )
126 * }
127 * ```
128 * @example
129 * A dependent query, only enabled once `postId` is set:
130 * ```tsx
131 * import { Match, Switch } from 'solid-js'
132 * import { useQuery } from '@tanstack/solid-query'
133 *
134 * function Post(props: { postId: number | undefined }) {
135 * const postQuery = useQuery(() => ({
136 * queryKey: ['post', props.postId],
137 * queryFn: () => fetchPost(props.postId!),
138 * enabled: props.postId != null,
139 * }))
140 *
141 * return (
142 * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
143 * <Match when={props.postId == null}>Select a post</Match>
144 * <Match when={postQuery.isLoading}>Loading...</Match>
145 * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
146 * </Switch>
147 * )
148 * }
149 * ```
150 * @example
151 * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
152 * `enabled`. The non-null assertion is still needed β Solid's `props` narrowing doesn't survive into the
153 * `queryFn` closure the way a local `const` would β but `skipToken` keeps `queryFn`'s return type accurate
154 * without it. `refetch` doesn't work while `queryFn` is `skipToken` β use `enabled: false` instead if you
155 * need to trigger the query manually:
156 * ```tsx
157 * import { Match, Switch } from 'solid-js'
158 * import { skipToken, useQuery } from '@tanstack/solid-query'
159 *
160 * function Post(props: { postId: number | undefined }) {
161 * const postQuery = useQuery(() => ({
162 * queryKey: ['post', props.postId],
163 * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
164 * }))
165 *
166 * return (
167 * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
168 * <Match when={props.postId == null}>Select a post</Match>
169 * <Match when={postQuery.isLoading}>Loading...</Match>
170 * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
171 * </Switch>
172 * )
173 * }
174 * ```
175 * @example
176 * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
177 * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
178 * fetched rather than from now:
179 * ```tsx
180 * import { useQuery, useQueryClient } from '@tanstack/solid-query'
181 *
182 * function Post(props: { postId: number }) {
183 * const queryClient = useQueryClient()
184 *
185 * const postQuery = useQuery(() => ({
186 * queryKey: ['post', props.postId],
187 * queryFn: () => fetchPost(props.postId),
188 * initialData: () =>
189 * queryClient
190 * .getQueryData<Array<Post>>(['posts'])
191 * ?.find((post) => post.id === props.postId),
192 * initialDataUpdatedAt: () =>
193 * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
194 * }))
195 *
196 * return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
197 * }
198 * ```
199 * @example
200 * Paginated data, keeping the previous page's data visible while the next page loads:
201 * ```tsx
202 * import { For, createSignal } from 'solid-js'
203 * import { keepPreviousData, useQuery } from '@tanstack/solid-query'
204 *
205 * function Posts() {
206 * const [page, setPage] = createSignal(0)
207 *
208 * const postsQuery = useQuery(() => ({
209 * queryKey: ['posts', page()],
210 * queryFn: () => fetchPosts(page()),
211 * placeholderData: keepPreviousData,
212 * }))
213 *
214 * return (
215 * <div>
216 * <ul>
217 * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
218 * </ul>
219 * <button
220 * disabled={postsQuery.isPlaceholderData}
221 * onClick={() => setPage((old) => old + 1)}
222 * >
223 * Next Page
224 * </button>
225 * </div>
226 * )
227 * }
228 * ```
229 */
230export function useQuery<
231 TQueryFnData = unknown,
232 TError = DefaultError,
233 TData = TQueryFnData,
234 TQueryKey extends QueryKey = QueryKey,
235>(
236 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
237 queryClient?: () => QueryClient,
238): UseQueryResult<TData, TError>
239export function useQuery<
240 TQueryFnData,
241 TError = DefaultError,
242 TData = TQueryFnData,
243 TQueryKey extends QueryKey = QueryKey,
244>(
245 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
246 queryClient?: Accessor<QueryClient>,
247) {
248 return useBaseQuery(
249 createMemo(() => options()),
250 QueryObserver,
251 queryClient,
252 )
253}