@tanstack/solid-query 5.107.1 → 5.107.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.d.ts CHANGED
@@ -261,860 +261,862 @@ type UseBaseMutationResult<TData = unknown, TError = DefaultError, TVariables =
261
261
  */
262
262
  type UseMutationResult<TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown> = UseBaseMutationResult<TData, TError, TVariables, TOnMutateResult>;
263
263
  /**
264
- * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be
264
+ * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be
265
265
  * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is
266
- * `pending`. `queryOptions` itself accepts and returns a plain object (its parameter type is
267
- * `ReturnType<UndefinedInitialDataOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity applies
268
- * where the result is consumed instead, e.g. `useQuery(() => options)`.
269
- * @template TQueryFnData - The type your `queryFn` resolves to.
266
+ * `pending`. `infiniteQueryOptions` itself accepts and returns a plain object (its parameter type is
267
+ * `ReturnType<UndefinedInitialDataInfiniteOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity
268
+ * applies where the result is consumed instead, e.g. `useInfiniteQuery(() => options)`.
269
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
270
270
  * @template TError - The type of errors your `queryFn` may throw.
271
- * @template TData - The type `data` ends up as after `select` runs.
271
+ * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
272
+ * the shape of all fetched pages plus their page params.
272
273
  * @template TQueryKey - The type of your `queryKey`.
274
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
273
275
  */
274
- type UndefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Accessor<QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
275
- initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
276
+ type UndefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = Accessor<InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
277
+ initialData?: undefined | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | InitialDataFunction<NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>>;
276
278
  }>;
277
279
  /**
278
- * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined —
279
- * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
280
- * @template TQueryFnData - The type your `queryFn` resolves to.
280
+ * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be
281
+ * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
282
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
281
283
  * @template TError - The type of errors your `queryFn` may throw.
282
- * @template TData - The type `data` ends up as after `select` runs.
284
+ * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
285
+ * the shape of all fetched pages plus their page params.
283
286
  * @template TQueryKey - The type of your `queryKey`.
287
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
284
288
  */
285
- type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Accessor<QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
286
- initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
289
+ type DefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = Accessor<InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
290
+ initialData: NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>);
287
291
  }>;
288
292
  /**
289
- * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
290
- * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
291
- * is the query key to generate options for.
293
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
294
+ * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
295
+ * `options.queryKey` is required and is the query key to generate options for.
292
296
  *
293
- * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
294
- * `undefined` (unless a `select` changes `TData` to include `undefined`).
295
- * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined.
297
+ * This overload is selected when `initialData` is known to be defined.
298
+ * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined.
296
299
  * @returns The same options object, typed so that `queryKey` carries the inferred data type.
297
- * @see {@link useQuery} to run a query with these options.
300
+ * @see {@link useInfiniteQuery} to run an infinite query with these options.
298
301
  * @example
299
302
  * ```tsx
300
303
  * import { For } from 'solid-js'
301
- * import { queryOptions, useQuery } from '@tanstack/solid-query'
304
+ * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'
302
305
  *
303
- * const postsOptions = queryOptions({
304
- * queryKey: ['posts'],
305
- * queryFn: fetchPosts,
306
- * initialData: [],
306
+ * const projectsOptions = infiniteQueryOptions({
307
+ * queryKey: ['projects'],
308
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
309
+ * initialPageParam: 0,
310
+ * getNextPageParam: (lastPage) => lastPage.nextId,
311
+ * initialData: { pages: [], pageParams: [] },
307
312
  * })
308
313
  *
309
- * function Posts() {
310
- * // `postsQuery.data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
311
- * // so the list stays visible alongside the error.
312
- * const postsQuery = useQuery(() => postsOptions)
314
+ * function Projects() {
315
+ * // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
316
+ * // list stays visible alongside the error.
317
+ * const projectsQuery = useInfiniteQuery(() => projectsOptions)
313
318
  *
314
319
  * return (
315
320
  * <div>
316
- * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
321
+ * {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
317
322
  * <ul>
318
- * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
323
+ * <For each={projectsQuery.data.pages}>
324
+ * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
325
+ * </For>
319
326
  * </ul>
320
327
  * </div>
321
328
  * )
322
329
  * }
323
330
  * ```
324
331
  */
325
- export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: ReturnType<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>): ReturnType<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
332
+ export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: ReturnType<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>): ReturnType<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
326
333
  /**
327
- * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
328
- * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
329
- * is the query key to generate options for.
330
- * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
334
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
335
+ * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
336
+ * `options.queryKey` is required and is the query key to generate options for.
337
+ * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
331
338
  * @returns The same options object, typed so that `queryKey` carries the inferred data type.
332
- * @see {@link useQuery} to run a query with these options.
339
+ * @see {@link useInfiniteQuery} to run an infinite query with these options.
333
340
  * @example
334
- * A parameterized factory, so the same options object can be reused per `id`:
341
+ * A parameterized factory, so the same options object can be reused per `postId`:
335
342
  * ```tsx
336
- * import { Match, Switch } from 'solid-js'
337
- * import { queryOptions, useQuery } from '@tanstack/solid-query'
343
+ * import { For, Match, Switch } from 'solid-js'
344
+ * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'
338
345
  *
339
- * const postOptions = (id: string) =>
340
- * queryOptions({
341
- * queryKey: ['post', id],
342
- * queryFn: () => fetchPost(id),
346
+ * const commentsOptions = (postId: string) =>
347
+ * infiniteQueryOptions({
348
+ * queryKey: ['post', postId, 'comments'],
349
+ * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
350
+ * initialPageParam: 0,
351
+ * getNextPageParam: (lastPage) => lastPage.nextId,
343
352
  * })
344
353
  *
345
- * function Post(props: { id: string }) {
346
- * const postQuery = useQuery(() => postOptions(props.id))
354
+ * function Comments(props: { postId: string }) {
355
+ * const commentsQuery = useInfiniteQuery(() => commentsOptions(props.postId))
347
356
  *
348
357
  * return (
349
358
  * <Switch>
350
- * <Match when={postQuery.isPending}>Loading...</Match>
351
- * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
352
- * <Match when={postQuery.isSuccess}>
353
- * <h1>{postQuery.data.title}</h1>
359
+ * <Match when={commentsQuery.isPending}>Loading...</Match>
360
+ * <Match when={commentsQuery.isError}>Error: {commentsQuery.error.message}</Match>
361
+ * <Match when={commentsQuery.isSuccess}>
362
+ * <ul>
363
+ * <For each={commentsQuery.data.pages}>
364
+ * {(page) => <For each={page.comments}>{(c) => <li>{c.text}</li>}</For>}
365
+ * </For>
366
+ * </ul>
354
367
  * </Match>
355
368
  * </Switch>
356
369
  * )
357
370
  * }
358
371
  * ```
359
372
  */
360
- export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: ReturnType<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>): ReturnType<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
373
+ export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: ReturnType<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>): ReturnType<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
361
374
  /**
362
- * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
363
- * The query runs when the options call for it — `enabled: false` skips the initial fetch.
375
+ * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
376
+ * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
364
377
  *
365
- * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
366
- * `undefined` (unless a `select` changes `TData` to include `undefined`).
367
- * @param options - An accessor returning the {@link DefinedInitialDataOptions} to use — everything you can
368
- * pass to `useQuery`, with `initialData` known to be defined.
378
+ * This overload is selected when `initialData` is known to be defined.
379
+ * @param options - An accessor returning the {@link DefinedInitialDataInfiniteOptions} to use — everything
380
+ * you can pass to `useInfiniteQuery`, with `initialData` known to be defined.
369
381
  * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
370
382
  * will be used.
371
- * @returns The current query result, as a Solid store, typed so that `status` is `success` — or `error` if a
372
- * fetch attempt fails while keeping the existing data (`status` never resolves to `pending` in this overload's
373
- * type, since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for
374
- * convenience.
375
- * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
383
+ * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
384
+ * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
385
+ * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
386
+ * `InfiniteData<TQueryFnData>` shape.
387
+ * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
388
+ * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
389
+ * actions, or add conditions like `hasNextPage && !isFetching`.
390
+ * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
376
391
  * @example
377
392
  * ```tsx
378
393
  * import { For } from 'solid-js'
379
- * import { useQuery } from '@tanstack/solid-query'
394
+ * import { useInfiniteQuery } from '@tanstack/solid-query'
380
395
  *
381
- * function Posts() {
382
- * // `postsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
396
+ * function Projects() {
397
+ * // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
383
398
  * // list stays visible alongside the error.
384
- * const postsQuery = useQuery(() => ({
385
- * queryKey: ['posts'],
386
- * queryFn: fetchPosts,
387
- * initialData: [],
399
+ * const projectsQuery = useInfiniteQuery(() => ({
400
+ * queryKey: ['projects'],
401
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
402
+ * initialPageParam: 0,
403
+ * getNextPageParam: (lastPage) => lastPage.nextId,
404
+ * initialData: { pages: [], pageParams: [] },
388
405
  * }))
389
406
  *
390
407
  * return (
391
408
  * <div>
392
- * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
409
+ * {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
393
410
  * <ul>
394
- * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
411
+ * <For each={projectsQuery.data.pages}>
412
+ * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
413
+ * </For>
395
414
  * </ul>
396
415
  * </div>
397
416
  * )
398
417
  * }
399
418
  * ```
400
419
  */
401
- export declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
420
+ export declare function useInfiniteQuery<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): DefinedUseInfiniteQueryResult<TData, TError>;
402
421
  /**
403
- * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
404
- * The query runs when the options call for it — `enabled: false` skips the initial fetch.
405
- * @param options - An accessor returning the {@link UndefinedInitialDataOptions} to use — everything you can
406
- * pass to `useQuery`.
422
+ * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
423
+ * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
424
+ * @param options - An accessor returning the {@link UndefinedInitialDataInfiniteOptions} to use — everything
425
+ * you can pass to `useInfiniteQuery`.
407
426
  * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
408
427
  * will be used.
409
- * @returns The current query result, as a Solid store. `status` is `pending` if there is no cached data to
410
- * display, `error` if the last fetch attempt failed, or `success` if the query has data to display.
411
- * `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
412
- * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
428
+ * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
429
+ * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
430
+ * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
431
+ * `InfiniteData<TQueryFnData>` shape.
432
+ * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
433
+ * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
434
+ * actions, or add conditions like `hasNextPage && !isFetching`.
435
+ * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
413
436
  * @example
437
+ * Fetching the next page from a "Load More" button click:
414
438
  * ```tsx
415
439
  * import { For, Match, Switch } from 'solid-js'
416
- * import { useQuery } from '@tanstack/solid-query'
440
+ * import { useInfiniteQuery } from '@tanstack/solid-query'
417
441
  *
418
- * function Posts() {
419
- * const postsQuery = useQuery(() => ({
420
- * queryKey: ['posts'],
421
- * queryFn: fetchPosts,
442
+ * function Projects() {
443
+ * const projectsQuery = useInfiniteQuery(() => ({
444
+ * queryKey: ['projects'],
445
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
446
+ * initialPageParam: 0,
447
+ * getNextPageParam: (lastPage) => lastPage.nextId,
422
448
  * }))
423
449
  *
424
450
  * return (
425
451
  * <Switch>
426
- * <Match when={postsQuery.isPending}>Loading...</Match>
427
- * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
428
- * <Match when={postsQuery.isSuccess}>
452
+ * <Match when={projectsQuery.isPending}>Loading...</Match>
453
+ * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
454
+ * <Match when={projectsQuery.isSuccess}>
429
455
  * <ul>
430
- * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
456
+ * <For each={projectsQuery.data.pages}>
457
+ * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
458
+ * </For>
431
459
  * </ul>
432
- * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
460
+ * <button
461
+ * onClick={() => projectsQuery.fetchNextPage()}
462
+ * disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
463
+ * >
464
+ * {projectsQuery.isFetchingNextPage
465
+ * ? 'Loading more...'
466
+ * : projectsQuery.hasNextPage
467
+ * ? 'Load More'
468
+ * : 'Nothing more to load'}
469
+ * </button>
433
470
  * </Match>
434
471
  * </Switch>
435
472
  * )
436
473
  * }
437
474
  * ```
438
475
  * @example
439
- * `select` derives whatever `data` a component needs from the cached value, without changing what's
440
- * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
476
+ * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
477
+ * sentinel element after the list:
441
478
  * ```tsx
442
- * import { Match, Switch } from 'solid-js'
443
- * import { useQuery } from '@tanstack/solid-query'
479
+ * import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
480
+ * import { useInfiniteQuery } from '@tanstack/solid-query'
444
481
  *
445
- * function PostCount() {
446
- * const postsQuery = useQuery(() => ({
447
- * queryKey: ['posts'],
448
- * queryFn: fetchPosts,
449
- * select: (posts) => posts.length,
482
+ * function Projects() {
483
+ * const projectsQuery = useInfiniteQuery(() => ({
484
+ * queryKey: ['projects'],
485
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
486
+ * initialPageParam: 0,
487
+ * getNextPageParam: (lastPage) => lastPage.nextId,
450
488
  * }))
451
489
  *
452
- * return (
453
- * <Switch>
454
- * <Match when={postsQuery.isPending}>Loading...</Match>
455
- * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
456
- * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
457
- * </Switch>
458
- * )
459
- * }
460
- * ```
461
- * @example
462
- * A dependent query, only enabled once `postId` is set:
463
- * ```tsx
464
- * import { Match, Switch } from 'solid-js'
465
- * import { useQuery } from '@tanstack/solid-query'
490
+ * let sentinelRef: HTMLDivElement | undefined
466
491
  *
467
- * function Post(props: { postId: number | undefined }) {
468
- * const postQuery = useQuery(() => ({
469
- * queryKey: ['post', props.postId],
470
- * queryFn: () => fetchPost(props.postId!),
471
- * enabled: props.postId != null,
472
- * }))
492
+ * createEffect(() => {
493
+ * if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
473
494
  *
474
- * return (
475
- * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
476
- * <Match when={props.postId == null}>Select a post</Match>
477
- * <Match when={postQuery.isLoading}>Loading...</Match>
478
- * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
495
+ * const observer = new IntersectionObserver(([entry]) => {
496
+ * if (entry?.isIntersecting) projectsQuery.fetchNextPage()
497
+ * })
498
+ * observer.observe(sentinelRef)
499
+ *
500
+ * onCleanup(() => observer.disconnect())
501
+ * })
502
+ *
503
+ * return (
504
+ * <Switch>
505
+ * <Match when={projectsQuery.isPending}>Loading...</Match>
506
+ * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
507
+ * <Match when={projectsQuery.isSuccess}>
508
+ * <ul>
509
+ * <For each={projectsQuery.data.pages}>
510
+ * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
511
+ * </For>
512
+ * </ul>
513
+ * <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
514
+ * </Match>
479
515
  * </Switch>
480
516
  * )
481
517
  * }
482
518
  * ```
519
+ */
520
+ export declare function useInfiniteQuery<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): UseInfiniteQueryResult<TData, TError>;
521
+ /**
522
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
523
+ * `useMutation` is the primitive for that.
524
+ * @param options - An accessor returning the {@link UseMutationOptions} to use.
525
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
526
+ * will be used.
527
+ * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
528
+ * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
529
+ * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
530
+ * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
531
+ * the mutation settles removes the subscription and prevents them from firing.
483
532
  * @example
484
- * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
485
- * `enabled`. The non-null assertion is still needed — Solid's `props` narrowing doesn't survive into the
486
- * `queryFn` closure the way a local `const` would — but `skipToken` keeps `queryFn`'s return type accurate
487
- * without it. `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you
488
- * need to trigger the query manually:
489
533
  * ```tsx
490
- * import { Match, Switch } from 'solid-js'
491
- * import { skipToken, useQuery } from '@tanstack/solid-query'
534
+ * import { useMutation, useQueryClient } from '@tanstack/solid-query'
492
535
  *
493
- * function Post(props: { postId: number | undefined }) {
494
- * const postQuery = useQuery(() => ({
495
- * queryKey: ['post', props.postId],
496
- * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
536
+ * function TodoItem(props: { id: number }) {
537
+ * const queryClient = useQueryClient()
538
+ *
539
+ * const deleteTodoMutation = useMutation(() => ({
540
+ * mutationFn: deleteTodo,
541
+ * onSuccess: () => {
542
+ * queryClient.invalidateQueries({ queryKey: ['todos'] })
543
+ * },
497
544
  * }))
498
545
  *
499
546
  * return (
500
- * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
501
- * <Match when={props.postId == null}>Select a post</Match>
502
- * <Match when={postQuery.isLoading}>Loading...</Match>
503
- * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
504
- * </Switch>
547
+ * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
548
+ * Delete
549
+ * </button>
505
550
  * )
506
551
  * }
507
552
  * ```
508
553
  * @example
509
- * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
510
- * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
511
- * fetched rather than from now:
554
+ * Rendering the mutation's own state, rather than just firing it off:
512
555
  * ```tsx
513
- * import { useQuery, useQueryClient } from '@tanstack/solid-query'
556
+ * import { Match, Switch } from 'solid-js'
557
+ * import { useMutation, useQueryClient } from '@tanstack/solid-query'
514
558
  *
515
- * function Post(props: { postId: number }) {
559
+ * function AddTodo() {
516
560
  * const queryClient = useQueryClient()
517
561
  *
518
- * const postQuery = useQuery(() => ({
519
- * queryKey: ['post', props.postId],
520
- * queryFn: () => fetchPost(props.postId),
521
- * initialData: () =>
522
- * queryClient
523
- * .getQueryData<Array<Post>>(['posts'])
524
- * ?.find((post) => post.id === props.postId),
525
- * initialDataUpdatedAt: () =>
526
- * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
562
+ * const addMutation = useMutation(() => ({
563
+ * mutationFn: addTodo,
564
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
527
565
  * }))
528
566
  *
529
- * return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
567
+ * return (
568
+ * <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
569
+ * <Match when={addMutation.isPending}>Adding todo...</Match>
570
+ * <Match when={addMutation.isError}>
571
+ * <div>An error occurred: {addMutation.error?.message}</div>
572
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
573
+ * </Match>
574
+ * </Switch>
575
+ * )
530
576
  * }
531
577
  * ```
532
578
  * @example
533
- * Paginated data, keeping the previous page's data visible while the next page loads:
579
+ * Optimistic update via `onMutate`, rolling back on `onError`:
534
580
  * ```tsx
535
- * import { For, createSignal } from 'solid-js'
536
- * import { keepPreviousData, useQuery } from '@tanstack/solid-query'
581
+ * import { useMutation, useQueryClient } from '@tanstack/solid-query'
537
582
  *
538
- * function Posts() {
539
- * const [page, setPage] = createSignal(0)
583
+ * function AddTodo() {
584
+ * const queryClient = useQueryClient()
540
585
  *
541
- * const postsQuery = useQuery(() => ({
542
- * queryKey: ['posts', page()],
543
- * queryFn: () => fetchPosts(page()),
544
- * placeholderData: keepPreviousData,
586
+ * const addMutation = useMutation(() => ({
587
+ * mutationFn: addTodo,
588
+ * onMutate: async (newTodo) => {
589
+ * await queryClient.cancelQueries({ queryKey: ['todos'] })
590
+ * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
591
+ *
592
+ * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
593
+ * ...(old ?? []),
594
+ * newTodo,
595
+ * ])
596
+ *
597
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
598
+ * return { previousTodos }
599
+ * },
600
+ * onError: (_err, _newTodo, onMutateResult) => {
601
+ * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
602
+ * },
603
+ * onSettled: () => {
604
+ * queryClient.invalidateQueries({ queryKey: ['todos'] })
605
+ * },
545
606
  * }))
546
607
  *
547
608
  * return (
548
- * <div>
549
- * <ul>
550
- * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
551
- * </ul>
552
- * <button
553
- * disabled={postsQuery.isPlaceholderData}
554
- * onClick={() => setPage((old) => old + 1)}
555
- * >
556
- * Next Page
557
- * </button>
558
- * </div>
609
+ * <button onClick={() => addMutation.mutate('Item')}>Add</button>
559
610
  * )
560
611
  * }
561
612
  * ```
562
- */
563
- export declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
564
- /**
565
- * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be
566
- * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is
567
- * `pending`. `infiniteQueryOptions` itself accepts and returns a plain object (its parameter type is
568
- * `ReturnType<UndefinedInitialDataInfiniteOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity
569
- * applies where the result is consumed instead, e.g. `useInfiniteQuery(() => options)`.
570
- * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
571
- * @template TError - The type of errors your `queryFn` may throw.
572
- * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
573
- * the shape of all fetched pages plus their page params.
574
- * @template TQueryKey - The type of your `queryKey`.
575
- * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
576
- */
577
- type UndefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = Accessor<InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
578
- initialData?: undefined | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | InitialDataFunction<NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>>;
579
- }>;
580
- /**
581
- * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be
582
- * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
583
- * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
584
- * @template TError - The type of errors your `queryFn` may throw.
585
- * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
586
- * the shape of all fetched pages plus their page params.
587
- * @template TQueryKey - The type of your `queryKey`.
588
- * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
589
- */
590
- type DefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = Accessor<InfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
591
- initialData: NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>);
592
- }>;
593
- /**
594
- * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
595
- * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
596
- * `options.queryKey` is required and is the query key to generate options for.
597
- *
598
- * This overload is selected when `initialData` is known to be defined.
599
- * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined.
600
- * @returns The same options object, typed so that `queryKey` carries the inferred data type.
601
- * @see {@link useInfiniteQuery} to run an infinite query with these options.
602
613
  * @example
614
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
615
+ * promise per call instead, so you can wait for all of them when they succeed:
603
616
  * ```tsx
604
- * import { For } from 'solid-js'
605
- * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'
617
+ * import { useMutation, useQueryClient } from '@tanstack/solid-query'
606
618
  *
607
- * const projectsOptions = infiniteQueryOptions({
608
- * queryKey: ['projects'],
609
- * queryFn: ({ pageParam }) => fetchProjects(pageParam),
610
- * initialPageParam: 0,
611
- * getNextPageParam: (lastPage) => lastPage.nextId,
612
- * initialData: { pages: [], pageParams: [] },
613
- * })
619
+ * function AddTodos() {
620
+ * const queryClient = useQueryClient()
614
621
  *
615
- * function Projects() {
616
- * // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
617
- * // list stays visible alongside the error.
618
- * const projectsQuery = useInfiniteQuery(() => projectsOptions)
622
+ * const addMutation = useMutation(() => ({
623
+ * mutationFn: addTodo,
624
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
625
+ * }))
626
+ *
627
+ * async function handleAddAll(todos: Array<string>) {
628
+ * try {
629
+ * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
630
+ * } catch (error) {
631
+ * console.error('Failed to add todos:', error)
632
+ * }
633
+ * }
619
634
  *
620
635
  * return (
621
- * <div>
622
- * {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
623
- * <ul>
624
- * <For each={projectsQuery.data.pages}>
625
- * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
626
- * </For>
627
- * </ul>
628
- * </div>
636
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
637
+ * Add all
638
+ * </button>
629
639
  * )
630
640
  * }
631
641
  * ```
632
- */
633
- export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: ReturnType<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>): ReturnType<DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
634
- /**
635
- * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
636
- * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`.
637
- * `options.queryKey` is required and is the query key to generate options for.
638
- * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
639
- * @returns The same options object, typed so that `queryKey` carries the inferred data type.
640
- * @see {@link useInfiniteQuery} to run an infinite query with these options.
641
642
  * @example
642
- * A parameterized factory, so the same options object can be reused per `postId`:
643
+ * If some of the mutations above can fail independently of the others, and you want to know which ones
644
+ * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
645
+ * `Promise.allSettled`:
643
646
  * ```tsx
644
- * import { For, Match, Switch } from 'solid-js'
645
- * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/solid-query'
647
+ * import { useMutation, useQueryClient } from '@tanstack/solid-query'
646
648
  *
647
- * const commentsOptions = (postId: string) =>
648
- * infiniteQueryOptions({
649
- * queryKey: ['post', postId, 'comments'],
650
- * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
651
- * initialPageParam: 0,
652
- * getNextPageParam: (lastPage) => lastPage.nextId,
653
- * })
649
+ * function AddTodos() {
650
+ * const queryClient = useQueryClient()
654
651
  *
655
- * function Comments(props: { postId: string }) {
656
- * const commentsQuery = useInfiniteQuery(() => commentsOptions(props.postId))
652
+ * const addMutation = useMutation(() => ({
653
+ * mutationFn: addTodo,
654
+ * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
655
+ * }))
657
656
  *
658
- * return (
659
- * <Switch>
660
- * <Match when={commentsQuery.isPending}>Loading...</Match>
661
- * <Match when={commentsQuery.isError}>Error: {commentsQuery.error.message}</Match>
662
- * <Match when={commentsQuery.isSuccess}>
663
- * <ul>
664
- * <For each={commentsQuery.data.pages}>
665
- * {(page) => <For each={page.comments}>{(c) => <li>{c.text}</li>}</For>}
666
- * </For>
667
- * </ul>
668
- * </Match>
669
- * </Switch>
657
+ * async function handleAddAll(todos: Array<string>) {
658
+ * const addResults = await Promise.allSettled(
659
+ * todos.map((todo) => addMutation.mutateAsync(todo)),
660
+ * )
661
+ *
662
+ * addResults.forEach((addResult, index) => {
663
+ * if (addResult.status === 'rejected') {
664
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
665
+ * }
666
+ * })
667
+ * }
668
+ *
669
+ * return (
670
+ * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
671
+ * Add all
672
+ * </button>
670
673
  * )
671
674
  * }
672
675
  * ```
673
676
  */
674
- export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: ReturnType<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>>): ReturnType<UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
677
+ export declare function useMutation<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: Accessor<QueryClient>): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
678
+ type UseQueryOptionsForUseQueries<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<QueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'placeholderData' | 'suspense'> & {
679
+ placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>;
680
+ /**
681
+ * @deprecated The `suspense` option has been deprecated in v5 and will be removed in the next major version.
682
+ * The `data` property on useQueries is a plain object and not a SolidJS Resource.
683
+ * It will not suspend when the data is loading.
684
+ * Setting `suspense` to `true` will be a no-op.
685
+ */
686
+ suspense?: boolean;
687
+ };
688
+ type MAXIMUM_DEPTH = 20;
689
+ type SkipTokenForUseQueries = symbol;
690
+ type GetOptions<T> = T extends {
691
+ queryFnData: infer TQueryFnData;
692
+ error?: infer TError;
693
+ data: infer TData;
694
+ } ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData> : T extends {
695
+ queryFnData: infer TQueryFnData;
696
+ error?: infer TError;
697
+ } ? UseQueryOptionsForUseQueries<TQueryFnData, TError> : T extends {
698
+ data: infer TData;
699
+ error?: infer TError;
700
+ } ? UseQueryOptionsForUseQueries<unknown, TError, TData> : T extends [infer TQueryFnData, infer TError, infer TData] ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData> : T extends [infer TQueryFnData, infer TError] ? UseQueryOptionsForUseQueries<TQueryFnData, TError> : T extends [infer TQueryFnData] ? UseQueryOptionsForUseQueries<TQueryFnData> : T extends {
701
+ queryFn?: QueryFunction<infer TQueryFnData, infer TQueryKey> | SkipTokenForUseQueries;
702
+ select?: (data: any) => infer TData;
703
+ throwOnError?: ThrowOnError<any, infer TError, any, any>;
704
+ } ? UseQueryOptionsForUseQueries<TQueryFnData, unknown extends TError ? DefaultError : TError, unknown extends TData ? TQueryFnData : TData, TQueryKey> : UseQueryOptionsForUseQueries;
705
+ type GetResults<T> = T extends {
706
+ queryFnData: any;
707
+ error?: infer TError;
708
+ data: infer TData;
709
+ } ? UseQueryResult<TData, TError> : T extends {
710
+ queryFnData: infer TQueryFnData;
711
+ error?: infer TError;
712
+ } ? UseQueryResult<TQueryFnData, TError> : T extends {
713
+ data: infer TData;
714
+ error?: infer TError;
715
+ } ? UseQueryResult<TData, TError> : T extends [any, infer TError, infer TData] ? UseQueryResult<TData, TError> : T extends [infer TQueryFnData, infer TError] ? UseQueryResult<TQueryFnData, TError> : T extends [infer TQueryFnData] ? UseQueryResult<TQueryFnData> : T extends {
716
+ queryFn?: QueryFunction<infer TQueryFnData, any> | SkipTokenForUseQueries;
717
+ select?: (data: any) => infer TData;
718
+ throwOnError?: ThrowOnError<any, infer TError, any, any>;
719
+ } ? UseQueryResult<unknown extends TData ? TQueryFnData : TData, unknown extends TError ? DefaultError : TError> : UseQueryResult;
675
720
  /**
676
- * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
677
- * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
721
+ * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param
722
+ */
723
+ type QueriesOptions<T extends Array<any>, TResult extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<UseQueryOptionsForUseQueries> : T extends [] ? [] : T extends [infer Head] ? [...TResult, GetOptions<Head>] : T extends [infer Head, ...infer Tail] ? QueriesOptions<[...Tail], [...TResult, GetOptions<Head>], [...TDepth, 1]> : ReadonlyArray<unknown> extends T ? T : T extends Array<UseQueryOptionsForUseQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<UseQueryOptionsForUseQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<UseQueryOptionsForUseQueries>;
724
+ /**
725
+ * QueriesResults reducer recursively maps type param to results
726
+ */
727
+ type QueriesResults<T extends Array<any>, TResult extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<UseQueryResult> : T extends [] ? [] : T extends [infer Head] ? [...TResult, GetResults<Head>] : T extends [infer Head, ...infer Tail] ? QueriesResults<[...Tail], [...TResult, GetResults<Head>], [...TDepth, 1]> : { [K in keyof T]: GetResults<T[K]>; };
728
+ /**
729
+ * The `useQueries` primitive can be used to fetch a variable number of queries.
678
730
  *
679
- * This overload is selected when `initialData` is known to be defined.
680
- * @param options - An accessor returning the {@link DefinedInitialDataInfiniteOptions} to use — everything
681
- * you can pass to `useInfiniteQuery`, with `initialData` known to be defined.
731
+ * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see
732
+ * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
733
+ * own top-level second argument, rather than per query.
734
+ *
735
+ * Having the same query key more than once in the array of query objects may cause some data to be shared
736
+ * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
737
+ * structure.
738
+ *
739
+ * The `combine` option can be used to combine the results of the queries into a single value. The result will
740
+ * be structurally shared to be as referentially stable as possible.
741
+ *
742
+ * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
743
+ * previously rendered queries, because the number of queries can differ between renders.
744
+ * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
745
+ * function.
682
746
  * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
683
747
  * will be used.
684
- * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
685
- * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
686
- * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
687
- * `InfiniteData<TQueryFnData>` shape.
688
- * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
689
- * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
690
- * actions, or add conditions like `hasNextPage && !isFetching`.
691
- * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
748
+ * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
749
+ * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
692
750
  * @example
693
751
  * ```tsx
694
752
  * import { For } from 'solid-js'
695
- * import { useInfiniteQuery } from '@tanstack/solid-query'
753
+ * import { useQueries } from '@tanstack/solid-query'
696
754
  *
697
- * function Projects() {
698
- * // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
699
- * // list stays visible alongside the error.
700
- * const projectsQuery = useInfiniteQuery(() => ({
701
- * queryKey: ['projects'],
702
- * queryFn: ({ pageParam }) => fetchProjects(pageParam),
703
- * initialPageParam: 0,
704
- * getNextPageParam: (lastPage) => lastPage.nextId,
705
- * initialData: { pages: [], pageParams: [] },
755
+ * function Posts(props: { ids: Array<number> }) {
756
+ * const postQueries = useQueries(() => ({
757
+ * queries: props.ids.map((id) => ({
758
+ * queryKey: ['post', id],
759
+ * queryFn: () => fetchPost(id),
760
+ * staleTime: Infinity,
761
+ * })),
706
762
  * }))
707
763
  *
708
764
  * return (
709
- * <div>
710
- * {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
711
- * <ul>
712
- * <For each={projectsQuery.data.pages}>
713
- * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
714
- * </For>
715
- * </ul>
716
- * </div>
765
+ * <ul>
766
+ * <For each={postQueries}>
767
+ * {(postQuery) => {
768
+ * if (postQuery.isPending) return <li>Loading...</li>
769
+ * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
770
+ * return <li>{postQuery.data.title}</li>
771
+ * }}
772
+ * </For>
773
+ * </ul>
717
774
  * )
718
775
  * }
719
776
  * ```
720
- */
721
- export declare function useInfiniteQuery<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): DefinedUseInfiniteQueryResult<TData, TError>;
722
- /**
723
- * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
724
- * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
725
- * @param options - An accessor returning the {@link UndefinedInitialDataInfiniteOptions} to use — everything
726
- * you can pass to `useInfiniteQuery`.
727
- * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
728
- * will be used.
729
- * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
730
- * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
731
- * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
732
- * `InfiniteData<TQueryFnData>` shape.
733
- * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
734
- * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
735
- * actions, or add conditions like `hasNextPage && !isFetching`.
736
- * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
737
777
  * @example
738
- * Fetching the next page from a "Load More" button click:
778
+ * Combining results into a single value:
739
779
  * ```tsx
740
780
  * import { For, Match, Switch } from 'solid-js'
741
- * import { useInfiniteQuery } from '@tanstack/solid-query'
781
+ * import { useQueries } from '@tanstack/solid-query'
742
782
  *
743
- * function Projects() {
744
- * const projectsQuery = useInfiniteQuery(() => ({
745
- * queryKey: ['projects'],
746
- * queryFn: ({ pageParam }) => fetchProjects(pageParam),
747
- * initialPageParam: 0,
748
- * getNextPageParam: (lastPage) => lastPage.nextId,
783
+ * function Posts(props: { ids: Array<number> }) {
784
+ * const combinedPostsQuery = useQueries(() => ({
785
+ * queries: props.ids.map((id) => ({
786
+ * queryKey: ['post', id],
787
+ * queryFn: () => fetchPost(id),
788
+ * })),
789
+ * combine: (postQueries) => {
790
+ * return {
791
+ * data: postQueries.map((postQuery) => postQuery.data),
792
+ * isPending: postQueries.some((postQuery) => postQuery.isPending),
793
+ * isError: postQueries.some((postQuery) => postQuery.isError),
794
+ * }
795
+ * },
749
796
  * }))
750
797
  *
751
798
  * return (
752
- * <Switch>
753
- * <Match when={projectsQuery.isPending}>Loading...</Match>
754
- * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
755
- * <Match when={projectsQuery.isSuccess}>
799
+ * <Switch
800
+ * fallback={
756
801
  * <ul>
757
- * <For each={projectsQuery.data.pages}>
758
- * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
759
- * </For>
802
+ * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
760
803
  * </ul>
761
- * <button
762
- * onClick={() => projectsQuery.fetchNextPage()}
763
- * disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
764
- * >
765
- * {projectsQuery.isFetchingNextPage
766
- * ? 'Loading more...'
767
- * : projectsQuery.hasNextPage
768
- * ? 'Load More'
769
- * : 'Nothing more to load'}
770
- * </button>
771
- * </Match>
804
+ * }
805
+ * >
806
+ * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
807
+ * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
772
808
  * </Switch>
773
809
  * )
774
810
  * }
775
811
  * ```
812
+ */
813
+ export declare function useQueries<T extends Array<any>, TCombinedResult extends QueriesResults<T> = QueriesResults<T>>(queriesOptions: Accessor<{
814
+ queries: readonly [...QueriesOptions<T>] | readonly [...{ [K in keyof T]: GetOptions<T[K]>; }];
815
+ combine?: (result: QueriesResults<T>) => TCombinedResult;
816
+ }>, queryClient?: Accessor<QueryClient>): TCombinedResult;
817
+ /**
818
+ * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be
819
+ * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is
820
+ * `pending`. `queryOptions` itself accepts and returns a plain object (its parameter type is
821
+ * `ReturnType<UndefinedInitialDataOptions<...>>`, i.e. this `Accessor` called); Solid's reactivity applies
822
+ * where the result is consumed instead, e.g. `useQuery(() => options)`.
823
+ * @template TQueryFnData - The type your `queryFn` resolves to.
824
+ * @template TError - The type of errors your `queryFn` may throw.
825
+ * @template TData - The type `data` ends up as after `select` runs.
826
+ * @template TQueryKey - The type of your `queryKey`.
827
+ */
828
+ type UndefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Accessor<QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
829
+ initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
830
+ }>;
831
+ /**
832
+ * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined —
833
+ * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
834
+ * @template TQueryFnData - The type your `queryFn` resolves to.
835
+ * @template TError - The type of errors your `queryFn` may throw.
836
+ * @template TData - The type `data` ends up as after `select` runs.
837
+ * @template TQueryKey - The type of your `queryKey`.
838
+ */
839
+ type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Accessor<QueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
840
+ initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
841
+ }>;
842
+ /**
843
+ * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
844
+ * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
845
+ * is the query key to generate options for.
846
+ *
847
+ * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
848
+ * `undefined` (unless a `select` changes `TData` to include `undefined`).
849
+ * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined.
850
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
851
+ * @see {@link useQuery} to run a query with these options.
776
852
  * @example
777
- * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
778
- * sentinel element after the list:
779
853
  * ```tsx
780
- * import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
781
- * import { useInfiniteQuery } from '@tanstack/solid-query'
782
- *
783
- * function Projects() {
784
- * const projectsQuery = useInfiniteQuery(() => ({
785
- * queryKey: ['projects'],
786
- * queryFn: ({ pageParam }) => fetchProjects(pageParam),
787
- * initialPageParam: 0,
788
- * getNextPageParam: (lastPage) => lastPage.nextId,
789
- * }))
854
+ * import { For } from 'solid-js'
855
+ * import { queryOptions, useQuery } from '@tanstack/solid-query'
790
856
  *
791
- * let sentinelRef: HTMLDivElement | undefined
857
+ * const postsOptions = queryOptions({
858
+ * queryKey: ['posts'],
859
+ * queryFn: fetchPosts,
860
+ * initialData: [],
861
+ * })
792
862
  *
793
- * createEffect(() => {
794
- * if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
863
+ * function Posts() {
864
+ * // `postsQuery.data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
865
+ * // so the list stays visible alongside the error.
866
+ * const postsQuery = useQuery(() => postsOptions)
795
867
  *
796
- * const observer = new IntersectionObserver(([entry]) => {
797
- * if (entry?.isIntersecting) projectsQuery.fetchNextPage()
798
- * })
799
- * observer.observe(sentinelRef)
868
+ * return (
869
+ * <div>
870
+ * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
871
+ * <ul>
872
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
873
+ * </ul>
874
+ * </div>
875
+ * )
876
+ * }
877
+ * ```
878
+ */
879
+ export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: ReturnType<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>): ReturnType<DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
880
+ /**
881
+ * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
882
+ * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
883
+ * is the query key to generate options for.
884
+ * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
885
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
886
+ * @see {@link useQuery} to run a query with these options.
887
+ * @example
888
+ * A parameterized factory, so the same options object can be reused per `id`:
889
+ * ```tsx
890
+ * import { Match, Switch } from 'solid-js'
891
+ * import { queryOptions, useQuery } from '@tanstack/solid-query'
800
892
  *
801
- * onCleanup(() => observer.disconnect())
893
+ * const postOptions = (id: string) =>
894
+ * queryOptions({
895
+ * queryKey: ['post', id],
896
+ * queryFn: () => fetchPost(id),
802
897
  * })
803
898
  *
899
+ * function Post(props: { id: string }) {
900
+ * const postQuery = useQuery(() => postOptions(props.id))
901
+ *
804
902
  * return (
805
903
  * <Switch>
806
- * <Match when={projectsQuery.isPending}>Loading...</Match>
807
- * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
808
- * <Match when={projectsQuery.isSuccess}>
809
- * <ul>
810
- * <For each={projectsQuery.data.pages}>
811
- * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
812
- * </For>
813
- * </ul>
814
- * <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
904
+ * <Match when={postQuery.isPending}>Loading...</Match>
905
+ * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
906
+ * <Match when={postQuery.isSuccess}>
907
+ * <h1>{postQuery.data.title}</h1>
815
908
  * </Match>
816
909
  * </Switch>
817
910
  * )
818
911
  * }
819
912
  * ```
820
913
  */
821
- export declare function useInfiniteQuery<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: Accessor<QueryClient>): UseInfiniteQueryResult<TData, TError>;
914
+ export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: ReturnType<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>>): ReturnType<UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
822
915
  /**
823
- * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
824
- * `useMutation` is the primitive for that.
825
- * @param options - An accessor returning the {@link UseMutationOptions} to use.
916
+ * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
917
+ * The query runs when the options call for it — `enabled: false` skips the initial fetch.
918
+ *
919
+ * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
920
+ * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
921
+ * if `select` throws on its first call.
922
+ * @param options - An accessor returning the {@link DefinedInitialDataOptions} to use — everything you can
923
+ * pass to `useQuery`, with `initialData` known to be defined.
826
924
  * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
827
925
  * will be used.
828
- * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
829
- * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
830
- * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
831
- * fire only for the latest call you've made, and only while the component is still mounted — unmounting before
832
- * the mutation settles removes the subscription and prevents them from firing.
926
+ * @returns The current query result, as a Solid store, typed so that `status` is `success` or `error`
927
+ * (`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront).
928
+ * `status` is `error` if the query has an error from a fetch that failed after its retries or if `select`
929
+ * threw, and `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
930
+ * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
833
931
  * @example
834
932
  * ```tsx
835
- * import { useMutation, useQueryClient } from '@tanstack/solid-query'
836
- *
837
- * function TodoItem(props: { id: number }) {
838
- * const queryClient = useQueryClient()
933
+ * import { For } from 'solid-js'
934
+ * import { useQuery } from '@tanstack/solid-query'
839
935
  *
840
- * const deleteTodoMutation = useMutation(() => ({
841
- * mutationFn: deleteTodo,
842
- * onSuccess: () => {
843
- * queryClient.invalidateQueries({ queryKey: ['todos'] })
844
- * },
936
+ * function Posts() {
937
+ * // `postsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
938
+ * // list stays visible alongside the error.
939
+ * const postsQuery = useQuery(() => ({
940
+ * queryKey: ['posts'],
941
+ * queryFn: fetchPosts,
942
+ * initialData: [],
845
943
  * }))
846
944
  *
847
945
  * return (
848
- * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
849
- * Delete
850
- * </button>
946
+ * <div>
947
+ * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
948
+ * <ul>
949
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
950
+ * </ul>
951
+ * </div>
851
952
  * )
852
953
  * }
853
954
  * ```
955
+ */
956
+ export declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): DefinedUseQueryResult<TData, TError>;
957
+ /**
958
+ * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
959
+ * The query runs when the options call for it — `enabled: false` skips the initial fetch.
960
+ * @param options - An accessor returning the {@link UndefinedInitialDataOptions} to use — everything you can
961
+ * pass to `useQuery`.
962
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
963
+ * will be used.
964
+ * @returns The current query result, as a Solid store. `status` is `error` if the query has an error from
965
+ * a fetch that failed after its retries or if `select` threw, `success` if the query has cached data
966
+ * (even if `select` returns `undefined`) or data from `placeholderData`, and `pending` otherwise.
967
+ * `isPending`/`isSuccess`/`isError` are derived booleans for convenience.
968
+ * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
854
969
  * @example
855
- * Rendering the mutation's own state, rather than just firing it off:
856
970
  * ```tsx
857
- * import { Match, Switch } from 'solid-js'
858
- * import { useMutation, useQueryClient } from '@tanstack/solid-query'
859
- *
860
- * function AddTodo() {
861
- * const queryClient = useQueryClient()
971
+ * import { For, Match, Switch } from 'solid-js'
972
+ * import { useQuery } from '@tanstack/solid-query'
862
973
  *
863
- * const addMutation = useMutation(() => ({
864
- * mutationFn: addTodo,
865
- * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
974
+ * function Posts() {
975
+ * const postsQuery = useQuery(() => ({
976
+ * queryKey: ['posts'],
977
+ * queryFn: fetchPosts,
866
978
  * }))
867
979
  *
868
980
  * return (
869
- * <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
870
- * <Match when={addMutation.isPending}>Adding todo...</Match>
871
- * <Match when={addMutation.isError}>
872
- * <div>An error occurred: {addMutation.error?.message}</div>
873
- * <button onClick={() => addMutation.mutate('Item')}>Add</button>
981
+ * <Switch>
982
+ * <Match when={postsQuery.isPending}>Loading...</Match>
983
+ * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
984
+ * <Match when={postsQuery.isSuccess}>
985
+ * <ul>
986
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
987
+ * </ul>
988
+ * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
874
989
  * </Match>
875
990
  * </Switch>
876
991
  * )
877
992
  * }
878
- * ```
879
- * @example
880
- * Optimistic update via `onMutate`, rolling back on `onError`:
881
- * ```tsx
882
- * import { useMutation, useQueryClient } from '@tanstack/solid-query'
883
- *
884
- * function AddTodo() {
885
- * const queryClient = useQueryClient()
886
- *
887
- * const addMutation = useMutation(() => ({
888
- * mutationFn: addTodo,
889
- * onMutate: async (newTodo) => {
890
- * await queryClient.cancelQueries({ queryKey: ['todos'] })
891
- * const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
892
- *
893
- * queryClient.setQueryData<Array<string>>(['todos'], (old) => [
894
- * ...(old ?? []),
895
- * newTodo,
896
- * ])
897
- *
898
- * // Passed to `onError` as `onMutateResult` if the mutation fails.
899
- * return { previousTodos }
900
- * },
901
- * onError: (_err, _newTodo, onMutateResult) => {
902
- * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
903
- * },
904
- * onSettled: () => {
905
- * queryClient.invalidateQueries({ queryKey: ['todos'] })
906
- * },
993
+ * ```
994
+ * @example
995
+ * `select` derives whatever `data` a component needs from the cached value, without changing what's
996
+ * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
997
+ * ```tsx
998
+ * import { Match, Switch } from 'solid-js'
999
+ * import { useQuery } from '@tanstack/solid-query'
1000
+ *
1001
+ * function PostCount() {
1002
+ * const postsQuery = useQuery(() => ({
1003
+ * queryKey: ['posts'],
1004
+ * queryFn: fetchPosts,
1005
+ * select: (posts) => posts.length,
907
1006
  * }))
908
1007
  *
909
1008
  * return (
910
- * <button onClick={() => addMutation.mutate('Item')}>Add</button>
1009
+ * <Switch>
1010
+ * <Match when={postsQuery.isPending}>Loading...</Match>
1011
+ * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
1012
+ * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
1013
+ * </Switch>
911
1014
  * )
912
1015
  * }
913
1016
  * ```
914
1017
  * @example
915
- * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
916
- * promise per call instead, so you can wait for all of them when they succeed:
1018
+ * A dependent query, only enabled once `postId` is set:
917
1019
  * ```tsx
918
- * import { useMutation, useQueryClient } from '@tanstack/solid-query'
919
- *
920
- * function AddTodos() {
921
- * const queryClient = useQueryClient()
1020
+ * import { Match, Switch } from 'solid-js'
1021
+ * import { useQuery } from '@tanstack/solid-query'
922
1022
  *
923
- * const addMutation = useMutation(() => ({
924
- * mutationFn: addTodo,
925
- * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
1023
+ * function Post(props: { postId: number | undefined }) {
1024
+ * const postQuery = useQuery(() => ({
1025
+ * queryKey: ['post', props.postId],
1026
+ * queryFn: () => fetchPost(props.postId!),
1027
+ * enabled: props.postId != null,
926
1028
  * }))
927
1029
  *
928
- * async function handleAddAll(todos: Array<string>) {
929
- * try {
930
- * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
931
- * } catch (error) {
932
- * console.error('Failed to add todos:', error)
933
- * }
934
- * }
935
- *
936
1030
  * return (
937
- * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
938
- * Add all
939
- * </button>
1031
+ * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
1032
+ * <Match when={props.postId == null}>Select a post</Match>
1033
+ * <Match when={postQuery.isLoading}>Loading...</Match>
1034
+ * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
1035
+ * </Switch>
940
1036
  * )
941
1037
  * }
942
1038
  * ```
943
1039
  * @example
944
- * If some of the mutations above can fail independently of the others, and you want to know which ones
945
- * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
946
- * `Promise.allSettled`:
1040
+ * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
1041
+ * `enabled`. The non-null assertion is still needed — Solid's `props` narrowing doesn't survive into the
1042
+ * `queryFn` closure the way a local `const` would — but `skipToken` keeps `queryFn`'s return type accurate
1043
+ * without it. `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you
1044
+ * need to trigger the query manually:
947
1045
  * ```tsx
948
- * import { useMutation, useQueryClient } from '@tanstack/solid-query'
949
- *
950
- * function AddTodos() {
951
- * const queryClient = useQueryClient()
1046
+ * import { Match, Switch } from 'solid-js'
1047
+ * import { skipToken, useQuery } from '@tanstack/solid-query'
952
1048
  *
953
- * const addMutation = useMutation(() => ({
954
- * mutationFn: addTodo,
955
- * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
1049
+ * function Post(props: { postId: number | undefined }) {
1050
+ * const postQuery = useQuery(() => ({
1051
+ * queryKey: ['post', props.postId],
1052
+ * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
956
1053
  * }))
957
1054
  *
958
- * async function handleAddAll(todos: Array<string>) {
959
- * const addResults = await Promise.allSettled(
960
- * todos.map((todo) => addMutation.mutateAsync(todo)),
961
- * )
962
- *
963
- * addResults.forEach((addResult, index) => {
964
- * if (addResult.status === 'rejected') {
965
- * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
966
- * }
967
- * })
968
- * }
969
- *
970
1055
  * return (
971
- * <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
972
- * Add all
973
- * </button>
1056
+ * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
1057
+ * <Match when={props.postId == null}>Select a post</Match>
1058
+ * <Match when={postQuery.isLoading}>Loading...</Match>
1059
+ * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
1060
+ * </Switch>
974
1061
  * )
975
1062
  * }
976
1063
  * ```
977
- */
978
- export declare function useMutation<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: Accessor<QueryClient>): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
979
- type UseQueryOptionsForUseQueries<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<QueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'placeholderData' | 'suspense'> & {
980
- placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>;
981
- /**
982
- * @deprecated The `suspense` option has been deprecated in v5 and will be removed in the next major version.
983
- * The `data` property on useQueries is a plain object and not a SolidJS Resource.
984
- * It will not suspend when the data is loading.
985
- * Setting `suspense` to `true` will be a no-op.
986
- */
987
- suspense?: boolean;
988
- };
989
- type MAXIMUM_DEPTH = 20;
990
- type SkipTokenForUseQueries = symbol;
991
- type GetOptions<T> = T extends {
992
- queryFnData: infer TQueryFnData;
993
- error?: infer TError;
994
- data: infer TData;
995
- } ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData> : T extends {
996
- queryFnData: infer TQueryFnData;
997
- error?: infer TError;
998
- } ? UseQueryOptionsForUseQueries<TQueryFnData, TError> : T extends {
999
- data: infer TData;
1000
- error?: infer TError;
1001
- } ? UseQueryOptionsForUseQueries<unknown, TError, TData> : T extends [infer TQueryFnData, infer TError, infer TData] ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData> : T extends [infer TQueryFnData, infer TError] ? UseQueryOptionsForUseQueries<TQueryFnData, TError> : T extends [infer TQueryFnData] ? UseQueryOptionsForUseQueries<TQueryFnData> : T extends {
1002
- queryFn?: QueryFunction<infer TQueryFnData, infer TQueryKey> | SkipTokenForUseQueries;
1003
- select?: (data: any) => infer TData;
1004
- throwOnError?: ThrowOnError<any, infer TError, any, any>;
1005
- } ? UseQueryOptionsForUseQueries<TQueryFnData, unknown extends TError ? DefaultError : TError, unknown extends TData ? TQueryFnData : TData, TQueryKey> : UseQueryOptionsForUseQueries;
1006
- type GetResults<T> = T extends {
1007
- queryFnData: any;
1008
- error?: infer TError;
1009
- data: infer TData;
1010
- } ? UseQueryResult<TData, TError> : T extends {
1011
- queryFnData: infer TQueryFnData;
1012
- error?: infer TError;
1013
- } ? UseQueryResult<TQueryFnData, TError> : T extends {
1014
- data: infer TData;
1015
- error?: infer TError;
1016
- } ? UseQueryResult<TData, TError> : T extends [any, infer TError, infer TData] ? UseQueryResult<TData, TError> : T extends [infer TQueryFnData, infer TError] ? UseQueryResult<TQueryFnData, TError> : T extends [infer TQueryFnData] ? UseQueryResult<TQueryFnData> : T extends {
1017
- queryFn?: QueryFunction<infer TQueryFnData, any> | SkipTokenForUseQueries;
1018
- select?: (data: any) => infer TData;
1019
- throwOnError?: ThrowOnError<any, infer TError, any, any>;
1020
- } ? UseQueryResult<unknown extends TData ? TQueryFnData : TData, unknown extends TError ? DefaultError : TError> : UseQueryResult;
1021
- /**
1022
- * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param
1023
- */
1024
- type QueriesOptions<T extends Array<any>, TResult extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<UseQueryOptionsForUseQueries> : T extends [] ? [] : T extends [infer Head] ? [...TResult, GetOptions<Head>] : T extends [infer Head, ...infer Tail] ? QueriesOptions<[...Tail], [...TResult, GetOptions<Head>], [...TDepth, 1]> : ReadonlyArray<unknown> extends T ? T : T extends Array<UseQueryOptionsForUseQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<UseQueryOptionsForUseQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<UseQueryOptionsForUseQueries>;
1025
- /**
1026
- * QueriesResults reducer recursively maps type param to results
1027
- */
1028
- type QueriesResults<T extends Array<any>, TResult extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<UseQueryResult> : T extends [] ? [] : T extends [infer Head] ? [...TResult, GetResults<Head>] : T extends [infer Head, ...infer Tail] ? QueriesResults<[...Tail], [...TResult, GetResults<Head>], [...TDepth, 1]> : { [K in keyof T]: GetResults<T[K]>; };
1029
- /**
1030
- * The `useQueries` primitive can be used to fetch a variable number of queries.
1031
- *
1032
- * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see
1033
- * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
1034
- * own top-level second argument, rather than per query.
1035
- *
1036
- * Having the same query key more than once in the array of query objects may cause some data to be shared
1037
- * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
1038
- * structure.
1039
- *
1040
- * The `combine` option can be used to combine the results of the queries into a single value. The result will
1041
- * be structurally shared to be as referentially stable as possible.
1042
- *
1043
- * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
1044
- * previously rendered queries, because the number of queries can differ between renders.
1045
- * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
1046
- * function.
1047
- * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
1048
- * will be used.
1049
- * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
1050
- * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
1051
1064
  * @example
1065
+ * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
1066
+ * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
1067
+ * fetched rather than from now:
1052
1068
  * ```tsx
1053
- * import { For } from 'solid-js'
1054
- * import { useQueries } from '@tanstack/solid-query'
1069
+ * import { useQuery, useQueryClient } from '@tanstack/solid-query'
1055
1070
  *
1056
- * function Posts(props: { ids: Array<number> }) {
1057
- * const postQueries = useQueries(() => ({
1058
- * queries: props.ids.map((id) => ({
1059
- * queryKey: ['post', id],
1060
- * queryFn: () => fetchPost(id),
1061
- * staleTime: Infinity,
1062
- * })),
1071
+ * function Post(props: { postId: number }) {
1072
+ * const queryClient = useQueryClient()
1073
+ *
1074
+ * const postQuery = useQuery(() => ({
1075
+ * queryKey: ['post', props.postId],
1076
+ * queryFn: () => fetchPost(props.postId),
1077
+ * initialData: () =>
1078
+ * queryClient
1079
+ * .getQueryData<Array<Post>>(['posts'])
1080
+ * ?.find((post) => post.id === props.postId),
1081
+ * initialDataUpdatedAt: () =>
1082
+ * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
1063
1083
  * }))
1064
1084
  *
1065
- * return (
1066
- * <ul>
1067
- * <For each={postQueries}>
1068
- * {(postQuery) => {
1069
- * if (postQuery.isPending) return <li>Loading...</li>
1070
- * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
1071
- * return <li>{postQuery.data.title}</li>
1072
- * }}
1073
- * </For>
1074
- * </ul>
1075
- * )
1085
+ * return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
1076
1086
  * }
1077
1087
  * ```
1078
1088
  * @example
1079
- * Combining results into a single value:
1089
+ * Paginated data, keeping the previous page's data visible while the next page loads:
1080
1090
  * ```tsx
1081
- * import { For, Match, Switch } from 'solid-js'
1082
- * import { useQueries } from '@tanstack/solid-query'
1091
+ * import { For, createSignal } from 'solid-js'
1092
+ * import { keepPreviousData, useQuery } from '@tanstack/solid-query'
1083
1093
  *
1084
- * function Posts(props: { ids: Array<number> }) {
1085
- * const combinedPostsQuery = useQueries(() => ({
1086
- * queries: props.ids.map((id) => ({
1087
- * queryKey: ['post', id],
1088
- * queryFn: () => fetchPost(id),
1089
- * })),
1090
- * combine: (postQueries) => {
1091
- * return {
1092
- * data: postQueries.map((postQuery) => postQuery.data),
1093
- * isPending: postQueries.some((postQuery) => postQuery.isPending),
1094
- * isError: postQueries.some((postQuery) => postQuery.isError),
1095
- * }
1096
- * },
1094
+ * function Posts() {
1095
+ * const [page, setPage] = createSignal(0)
1096
+ *
1097
+ * const postsQuery = useQuery(() => ({
1098
+ * queryKey: ['posts', page()],
1099
+ * queryFn: () => fetchPosts(page()),
1100
+ * placeholderData: keepPreviousData,
1097
1101
  * }))
1098
1102
  *
1099
1103
  * return (
1100
- * <Switch
1101
- * fallback={
1102
- * <ul>
1103
- * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
1104
- * </ul>
1105
- * }
1106
- * >
1107
- * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
1108
- * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
1109
- * </Switch>
1104
+ * <div>
1105
+ * <ul>
1106
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
1107
+ * </ul>
1108
+ * <button
1109
+ * disabled={postsQuery.isPlaceholderData}
1110
+ * onClick={() => setPage((old) => old + 1)}
1111
+ * >
1112
+ * Next Page
1113
+ * </button>
1114
+ * </div>
1110
1115
  * )
1111
1116
  * }
1112
1117
  * ```
1113
1118
  */
1114
- export declare function useQueries<T extends Array<any>, TCombinedResult extends QueriesResults<T> = QueriesResults<T>>(queriesOptions: Accessor<{
1115
- queries: readonly [...QueriesOptions<T>] | readonly [...{ [K in keyof T]: GetOptions<T[K]>; }];
1116
- combine?: (result: QueriesResults<T>) => TCombinedResult;
1117
- }>, queryClient?: Accessor<QueryClient>): TCombinedResult;
1119
+ export declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: () => QueryClient): UseQueryResult<TData, TError>;
1118
1120
  /**
1119
1121
  * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
1120
1122
  */