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

useQuery.ts

272 lines9.2 KB

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
19 * data that is tied to a unique key. The query runs when the options call for
20 * it β€” `enabled: false` skips the initial fetch.
21 *
22 * @example
23 * ;```tsx
24 * import { For, Match, Switch } from 'solid-js'
25 * import { useQuery } from '@tanstack/solid-query'
26 *
27 * function Posts() {
28 * const postsQuery = useQuery(() => ({
29 * queryKey: ['posts'],
30 * queryFn: fetchPosts,
31 * }))
32 *
33 * return (
34 * <Switch>
35 * <Match when={postsQuery.isPending}>Loading...</Match>
36 * <Match when={postsQuery.isError}>
37 * Error: {postsQuery.error.message}
38 * </Match>
39 * <Match when={postsQuery.isSuccess}>
40 * <ul>
41 * <For each={postsQuery.data}>
42 * {(post) => <li>{post.title}</li>}
43 * </For>
44 * </ul>
45 * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
46 * </Match>
47 * </Switch>
48 * )
49 * }
50 * ```
51 *
52 * @example
53 * `select` derives whatever `data` a component needs from the cached value, without changing what's
54 * actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
55 * ```tsx
56 * import { Match, Switch } from 'solid-js'
57 * import { useQuery } from '@tanstack/solid-query'
58 *
59 * function PostCount() {
60 * const postsQuery = useQuery(() => ({
61 * queryKey: ['posts'],
62 * queryFn: fetchPosts,
63 * select: (posts) => posts.length,
64 * }))
65 *
66 * return (
67 * <Switch>
68 * <Match when={postsQuery.isPending}>Loading...</Match>
69 * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
70 * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
71 * </Switch>
72 * )
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 *
99 * @example
100 * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
101 * `enabled`. The non-null assertion is still needed β€” Solid's `props` narrowing doesn't survive into the
102 * `queryFn` closure the way a local `const` would β€” but `skipToken` keeps `queryFn`'s return type accurate
103 * without it. `refetch` doesn't work while `queryFn` is `skipToken` β€” use `enabled: false` instead if you
104 * need to trigger the query manually:
105 * ```tsx
106 * import { Match, Switch } from 'solid-js'
107 * import { skipToken, useQuery } from '@tanstack/solid-query'
108 *
109 * function Post(props: { postId: number | undefined }) {
110 * const postQuery = useQuery(() => ({
111 * queryKey: ['post', props.postId],
112 * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
113 * }))
114 *
115 * return (
116 * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
117 * <Match when={props.postId == null}>Select a post</Match>
118 * <Match when={postQuery.isLoading}>Loading...</Match>
119 * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
120 * </Switch>
121 * )
122 * }
123 * ```
124 *
125 * @example
126 * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
127 * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
128 * fetched rather than from now:
129 * ```tsx
130 * import { useQuery, useQueryClient } from '@tanstack/solid-query'
131 *
132 * function Post(props: { postId: number }) {
133 * const queryClient = useQueryClient()
134 *
135 * const postQuery = useQuery(() => ({
136 * queryKey: ['post', props.postId],
137 * queryFn: () => fetchPost(props.postId),
138 * initialData: () =>
139 * queryClient
140 * .getQueryData<Array<Post>>(['posts'])
141 * ?.find((post) => post.id === props.postId),
142 * initialDataUpdatedAt: () =>
143 * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
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 *
181 * @param options - An accessor returning the
182 * {@link UndefinedInitialDataOptions} to use β€” everything you can pass to
183 * `useQuery`.
184 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the
185 * one from the nearest context will be used.
186 * @returns The current query result, as a Solid store. `status` is `pending` if
187 * there is no cached data to display, `error` if the last fetch attempt
188 * failed, or `success` if the query has data to display.
189 * `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
190 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
191 */
192export function useQuery<
193 TQueryFnData = unknown,
194 TError = DefaultError,
195 TData = TQueryFnData,
196 TQueryKey extends QueryKey = QueryKey,
197>(
198 options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
199 queryClient?: () => QueryClient,
200): UseQueryResult<TData, TError>
201​
202/**
203 * Subscribes to a query: a declarative dependency on an asynchronous source of
204 * data that is tied to a unique key. The query runs when the options call for
205 * it β€” `enabled: false` skips the initial fetch.
206 *
207 * This overload is selected when `initialData` is set, so the resulting `data`
208 * is never `undefined` (unless a `select` changes `TData` to include
209 * `undefined`).
210 *
211 * @example
212 * ```tsx
213 * import { For } from 'solid-js'
214 * import { useQuery } from '@tanstack/solid-query'
215 *
216 * function Posts() {
217 * // `postsQuery.data` is never `undefined`, thanks to `initialData` β€” even if a refetch fails, so the
218 * // list stays visible alongside the error.
219 * const postsQuery = useQuery(() => ({
220 * queryKey: ['posts'],
221 * queryFn: fetchPosts,
222 * initialData: [],
223 * }))
224 *
225 * return (
226 * <div>
227 * {postsQuery.isError ? (
228 * <span>Error: {postsQuery.error.message}</span>
229 * ) : null}
230 * <ul>
231 * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
232 * </ul>
233 * </div>
234 * )
235 * }
236 * ```
237 *
238 * @param options - An accessor returning the {@link DefinedInitialDataOptions}
239 * to use β€” everything you can pass to `useQuery`, with `initialData` set.
240 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the
241 * one from the nearest context will be used.
242 * @returns The current query result, as a Solid store, typed so that `status`
243 * is `success` β€” or `error` if a fetch attempt fails while keeping the
244 * existing data (`status` never resolves to `pending` in this overload's
245 * type, since `initialData` guarantees data upfront). `isSuccess`/`isError`
246 * are derived booleans for convenience.
247 * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
248 */
249export function useQuery<
250 TQueryFnData = unknown,
251 TError = DefaultError,
252 TData = TQueryFnData,
253 TQueryKey extends QueryKey = QueryKey,
254>(
255 options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
256 queryClient?: () => QueryClient,
257): DefinedUseQueryResult<TData, TError>
258export function useQuery<
259 TQueryFnData,
260 TError = DefaultError,
261 TData = TQueryFnData,
262 TQueryKey extends QueryKey = QueryKey,
263>(
264 options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
265 queryClient?: Accessor<QueryClient>,
266) {
267 return useBaseQuery(
268 createMemo(() => options()),
269 QueryObserver,
270 queryClient,
271 )