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