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

createQuery.ts

268 lines9.3 KB

1import { QueryObserver } from '@tanstack/query-core'
2import { createBaseQuery } from './createBaseQuery.svelte.js'
3import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
4import type {
5 DefinedInitialDataOptions,
6 UndefinedInitialDataOptions,
7} from './queryOptions.js'
8import type {
9 Accessor,
10 CreateQueryOptions,
11 CreateQueryResult,
12 DefinedCreateQueryResult,
13} from './types.js'
14​
15/**
16 * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
17 * The query runs when the options call for it β€” `enabled: false` skips the initial fetch.
18 *
19 * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
20 * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
21 * if `select` throws on its first call.
22 * @param options - The {@link DefinedInitialDataOptions} to use β€” everything you can pass to `createQuery`,
23 * with `initialData` known to be defined, wrapped in an {@link Accessor} so options can be reactive.
24 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
25 * be used.
26 * @returns The current query result, typed so that `status` is `success` or `error` (`status` never
27 * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is
28 * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and
29 * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
30 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
31 * @example
32 * ```svelte
33 * <script lang="ts">
34 * import { createQuery } from '@tanstack/svelte-query'
35 *
36 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β€” even if a refetch fails,
37 * // so the list stays visible alongside the error.
38 * const query = createQuery(() => ({
39 * queryKey: ['posts'],
40 * queryFn: fetchPosts,
41 * initialData: [],
42 * }))
43 * </script>
44 *
45 * {#if query.isError}
46 * <span>Error: {query.error.message}</span>
47 * {/if}
48 * <ul>
49 * {#each query.data as post (post.id)}
50 * <li>{post.title}</li>
51 * {/each}
52 * </ul>
53 * ```
54 */
55export function createQuery<
56 TQueryFnData = unknown,
57 TError = DefaultError,
58 TData = TQueryFnData,
59 TQueryKey extends QueryKey = QueryKey,
60>(
61 options: Accessor<
62 DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>
63 >,
64 queryClient?: Accessor<QueryClient>,
65): DefinedCreateQueryResult<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 - The {@link UndefinedInitialDataOptions} to use β€” everything you can pass to `createQuery`,
71 * wrapped in an {@link Accessor} so options can be reactive.
72 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
73 * be used.
74 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
75 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
76 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
77 * are derived booleans for convenience.
78 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
79 * @example
80 * ```svelte
81 * <script lang="ts">
82 * import { createQuery } from '@tanstack/svelte-query'
83 *
84 * const query = createQuery(() => ({
85 * queryKey: ['posts'],
86 * queryFn: fetchPosts,
87 * }))
88 * </script>
89 *
90 * {#if query.status === 'pending'}
91 * Loading...
92 * {:else if query.status === 'error'}
93 * <span>Error: {query.error.message}</span>
94 * {:else}
95 * <ul>
96 * {#each query.data as post (post.id)}
97 * <li>{post.title}</li>
98 * {/each}
99 * </ul>
100 * {/if}
101 * ```
102 * @example
103 * The same query, checking `isPending`/`isError` instead of `status` β€” pick whichever reads better to you:
104 * ```svelte
105 * <script lang="ts">
106 * import { createQuery } from '@tanstack/svelte-query'
107 *
108 * const query = createQuery(() => ({
109 * queryKey: ['posts'],
110 * queryFn: fetchPosts,
111 * }))
112 * </script>
113 *
114 * {#if query.isPending}
115 * Loading...
116 * {:else if query.isError}
117 * <span>Error: {query.error.message}</span>
118 * {:else}
119 * <ul>
120 * {#each query.data as post (post.id)}
121 * <li>{post.title}</li>
122 * {/each}
123 * </ul>
124 * {/if}
125 * ```
126 */
127export function createQuery<
128 TQueryFnData = unknown,
129 TError = DefaultError,
130 TData = TQueryFnData,
131 TQueryKey extends QueryKey = QueryKey,
132>(
133 options: Accessor<
134 UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>
135 >,
136 queryClient?: Accessor<QueryClient>,
137): CreateQueryResult<TData, TError>
138​
139/**
140 * Fallback overload for options whose `initialData` presence isn't statically known β€” for example, an
141 * object typed as {@link CreateQueryOptions} rather than an object literal. Prefer one of the other
142 * overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly.
143 * @param options - The {@link CreateQueryOptions} to use β€” everything you can pass to `createQuery`, wrapped
144 * in an {@link Accessor} so options can be reactive.
145 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
146 * be used.
147 * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed
148 * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns
149 * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError`
150 * are derived booleans for convenience.
151 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
152 * @example
153 * `select` derives whatever `data` a component needs from the cached value, without changing what's
154 * actually stored in the cache β€” the cache still holds the full `Post[]`, but `data` here is a `number`:
155 * ```svelte
156 * <script lang="ts">
157 * import { createQuery } from '@tanstack/svelte-query'
158 *
159 * const query = createQuery(() => ({
160 * queryKey: ['posts'],
161 * queryFn: fetchPosts,
162 * select: (posts) => posts.length,
163 * }))
164 * </script>
165 *
166 * {#if query.isPending}
167 * Loading...
168 * {:else if query.isError}
169 * <span>Error: {query.error.message}</span>
170 * {:else}
171 * <span>{query.data} posts</span>
172 * {/if}
173 * ```
174 * @example
175 * A dependent query, only enabled once `postId` is set β€” use `isLoading`, not `isPending`, so the
176 * loading state doesn't show while the query is disabled:
177 * ```svelte
178 * <script lang="ts">
179 * import { createQuery } from '@tanstack/svelte-query'
180 *
181 * let { postId }: { postId: number | undefined } = $props()
182 *
183 * const query = createQuery(() => ({
184 * queryKey: ['post', postId],
185 * queryFn: () => fetchPost(postId!),
186 * enabled: postId != null,
187 * }))
188 * </script>
189 *
190 * {#if postId == null}
191 * Select a post
192 * {:else if query.isLoading}
193 * Loading...
194 * {:else if query.isError}
195 * <span>Error: {query.error.message}</span>
196 * {:else}
197 * <h1>{query.data?.title}</h1>
198 * {/if}
199 * ```
200 * @example
201 * Seeding a detail query from an already-cached list, to skip the loading state:
202 * ```svelte
203 * <script lang="ts">
204 * import { createQuery, useQueryClient } from '@tanstack/svelte-query'
205 *
206 * let { postId }: { postId: number } = $props()
207 *
208 * const queryClient = useQueryClient()
209 *
210 * const query = createQuery(() => ({
211 * queryKey: ['post', postId],
212 * queryFn: () => fetchPost(postId),
213 * initialData: () =>
214 * queryClient
215 * .getQueryData<Array<Post>>(['posts'])
216 * ?.find((post) => post.id === postId),
217 * }))
218 * </script>
219 *
220 * {#if query.isError}
221 * <span>Error: {query.error.message}</span>
222 * {/if}
223 * <h1>{query.data?.title}</h1>
224 * ```
225 * @example
226 * Paginated data, keeping the previous page's data visible while the next page loads:
227 * ```svelte
228 * <script lang="ts">
229 * import { createQuery, keepPreviousData } from '@tanstack/svelte-query'
230 *
231 * let page = $state(0)
232 *
233 * const query = createQuery(() => ({
234 * queryKey: ['posts', page],
235 * queryFn: () => fetchPosts(page),
236 * placeholderData: keepPreviousData,
237 * }))
238 * </script>
239 *
240 * {#if query.isError}
241 * <span>Error: {query.error.message}</span>
242 * {/if}
243 * <ul>
244 * {#each query.data ?? [] as post (post.id)}
245 * <li>{post.title}</li>
246 * {/each}
247 * </ul>
248 * <button disabled={query.isPlaceholderData} onclick={() => page++}>
249 * Next Page
250 * </button>
251 * ```
252 */
253export function createQuery<
254 TQueryFnData,
255 TError = DefaultError,
256 TData = TQueryFnData,
257 TQueryKey extends QueryKey = QueryKey,
258>(
259 options: Accessor<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>>,
260 queryClient?: Accessor<QueryClient>,
261): CreateQueryResult<TData, TError>
262​
263export function createQuery(
264 options: Accessor<CreateQueryOptions>,
265 queryClient?: Accessor<QueryClient>,
266) {
267 return createBaseQuery(options, QueryObserver, queryClient)