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