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