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