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