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

createQuery.ts

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