diff --git a/docs/config.json b/docs/config.json index 10facefc7da..c9a0c6cf457 100644 --- a/docs/config.json +++ b/docs/config.json @@ -1013,84 +1013,268 @@ "label": "react", "children": [ { - "label": "useQuery", - "to": "framework/react/reference/useQuery" + "label": "React Reference", + "to": "framework/react/reference/index" }, { - "label": "useQueries", - "to": "framework/react/reference/useQueries" + "label": "Functions / useQuery", + "to": "framework/react/reference/functions/useQuery" }, { - "label": "useInfiniteQuery", - "to": "framework/react/reference/useInfiniteQuery" + "label": "Functions / useQueries", + "to": "framework/react/reference/functions/useQueries" }, { - "label": "useMutation", - "to": "framework/react/reference/useMutation" + "label": "Functions / useInfiniteQuery", + "to": "framework/react/reference/functions/useInfiniteQuery" }, { - "label": "useIsFetching", - "to": "framework/react/reference/useIsFetching" + "label": "Functions / useMutation", + "to": "framework/react/reference/functions/useMutation" }, { - "label": "useIsMutating", - "to": "framework/react/reference/useIsMutating" + "label": "Functions / useIsFetching", + "to": "framework/react/reference/functions/useIsFetching" }, { - "label": "useMutationState", - "to": "framework/react/reference/useMutationState" + "label": "Functions / useIsMutating", + "to": "framework/react/reference/functions/useIsMutating" }, { - "label": "useSuspenseQuery", - "to": "framework/react/reference/useSuspenseQuery" + "label": "Functions / useMutationState", + "to": "framework/react/reference/functions/useMutationState" }, { - "label": "useSuspenseInfiniteQuery", - "to": "framework/react/reference/useSuspenseInfiniteQuery" + "label": "Functions / useSuspenseQuery", + "to": "framework/react/reference/functions/useSuspenseQuery" }, { - "label": "useSuspenseQueries", - "to": "framework/react/reference/useSuspenseQueries" + "label": "Functions / useSuspenseInfiniteQuery", + "to": "framework/react/reference/functions/useSuspenseInfiniteQuery" }, { - "label": "QueryClientProvider", - "to": "framework/react/reference/QueryClientProvider" + "label": "Functions / useSuspenseQueries", + "to": "framework/react/reference/functions/useSuspenseQueries" }, { - "label": "useQueryClient", - "to": "framework/react/reference/useQueryClient" + "label": "Functions / QueryClientProvider", + "to": "framework/react/reference/functions/QueryClientProvider" }, { - "label": "queryOptions", - "to": "framework/react/reference/queryOptions" + "label": "Functions / useQueryClient", + "to": "framework/react/reference/functions/useQueryClient" }, { - "label": "infiniteQueryOptions", - "to": "framework/react/reference/infiniteQueryOptions" + "label": "Functions / queryOptions", + "to": "framework/react/reference/functions/queryOptions" }, { - "label": "mutationOptions", - "to": "framework/react/reference/mutationOptions" + "label": "Functions / infiniteQueryOptions", + "to": "framework/react/reference/functions/infiniteQueryOptions" }, { - "label": "usePrefetchQuery", - "to": "framework/react/reference/usePrefetchQuery" + "label": "Functions / mutationOptions", + "to": "framework/react/reference/functions/mutationOptions" }, { - "label": "usePrefetchInfiniteQuery", - "to": "framework/react/reference/usePrefetchInfiniteQuery" + "label": "Functions / usePrefetchQuery", + "to": "framework/react/reference/functions/usePrefetchQuery" }, { - "label": "QueryErrorResetBoundary", - "to": "framework/react/reference/QueryErrorResetBoundary" + "label": "Functions / usePrefetchInfiniteQuery", + "to": "framework/react/reference/functions/usePrefetchInfiniteQuery" }, { - "label": "useQueryErrorResetBoundary", - "to": "framework/react/reference/useQueryErrorResetBoundary" + "label": "Functions / QueryErrorResetBoundary", + "to": "framework/react/reference/functions/QueryErrorResetBoundary" }, { - "label": "hydration", - "to": "framework/react/reference/hydration" + "label": "Functions / useQueryErrorResetBoundary", + "to": "framework/react/reference/functions/useQueryErrorResetBoundary" + }, + { + "label": "Functions / HydrationBoundary", + "to": "framework/react/reference/functions/HydrationBoundary" + }, + { + "label": "Functions / useIsRestoring", + "to": "framework/react/reference/functions/useIsRestoring" + }, + { + "label": "Interfaces / HydrationBoundaryProps", + "to": "framework/react/reference/interfaces/HydrationBoundaryProps" + }, + { + "label": "Interfaces / QueryErrorResetBoundaryProps", + "to": "framework/react/reference/interfaces/QueryErrorResetBoundaryProps" + }, + { + "label": "Interfaces / UseBaseQueryOptions", + "to": "framework/react/reference/interfaces/UseBaseQueryOptions" + }, + { + "label": "Interfaces / UseInfiniteQueryOptions", + "to": "framework/react/reference/interfaces/UseInfiniteQueryOptions" + }, + { + "label": "Interfaces / UseMutationOptions", + "to": "framework/react/reference/interfaces/UseMutationOptions" + }, + { + "label": "Interfaces / UseQueryOptions", + "to": "framework/react/reference/interfaces/UseQueryOptions" + }, + { + "label": "Interfaces / UseSuspenseInfiniteQueryOptions", + "to": "framework/react/reference/interfaces/UseSuspenseInfiniteQueryOptions" + }, + { + "label": "Interfaces / UseSuspenseQueryOptions", + "to": "framework/react/reference/interfaces/UseSuspenseQueryOptions" + }, + { + "label": "Types / AnyUseBaseQueryOptions", + "to": "framework/react/reference/type-aliases/AnyUseBaseQueryOptions" + }, + { + "label": "Types / AnyUseInfiniteQueryOptions", + "to": "framework/react/reference/type-aliases/AnyUseInfiniteQueryOptions" + }, + { + "label": "Types / AnyUseMutationOptions", + "to": "framework/react/reference/type-aliases/AnyUseMutationOptions" + }, + { + "label": "Types / AnyUseQueryOptions", + "to": "framework/react/reference/type-aliases/AnyUseQueryOptions" + }, + { + "label": "Types / AnyUseSuspenseInfiniteQueryOptions", + "to": "framework/react/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions" + }, + { + "label": "Types / AnyUseSuspenseQueryOptions", + "to": "framework/react/reference/type-aliases/AnyUseSuspenseQueryOptions" + }, + { + "label": "Types / DefinedInitialDataInfiniteOptions", + "to": "framework/react/reference/type-aliases/DefinedInitialDataInfiniteOptions" + }, + { + "label": "Types / DefinedInitialDataOptions", + "to": "framework/react/reference/type-aliases/DefinedInitialDataOptions" + }, + { + "label": "Types / DefinedUseInfiniteQueryResult", + "to": "framework/react/reference/type-aliases/DefinedUseInfiniteQueryResult" + }, + { + "label": "Types / DefinedUseQueryResult", + "to": "framework/react/reference/type-aliases/DefinedUseQueryResult" + }, + { + "label": "Types / QueriesOptions", + "to": "framework/react/reference/type-aliases/QueriesOptions" + }, + { + "label": "Types / QueriesResults", + "to": "framework/react/reference/type-aliases/QueriesResults" + }, + { + "label": "Types / QueryClientProviderProps", + "to": "framework/react/reference/type-aliases/QueryClientProviderProps" + }, + { + "label": "Types / QueryErrorClearResetFunction", + "to": "framework/react/reference/type-aliases/QueryErrorClearResetFunction" + }, + { + "label": "Types / QueryErrorIsResetFunction", + "to": "framework/react/reference/type-aliases/QueryErrorIsResetFunction" + }, + { + "label": "Types / QueryErrorResetBoundaryFunction", + "to": "framework/react/reference/type-aliases/QueryErrorResetBoundaryFunction" + }, + { + "label": "Types / QueryErrorResetFunction", + "to": "framework/react/reference/type-aliases/QueryErrorResetFunction" + }, + { + "label": "Types / SuspenseQueriesOptions", + "to": "framework/react/reference/type-aliases/SuspenseQueriesOptions" + }, + { + "label": "Types / SuspenseQueriesResults", + "to": "framework/react/reference/type-aliases/SuspenseQueriesResults" + }, + { + "label": "Types / UndefinedInitialDataInfiniteOptions", + "to": "framework/react/reference/type-aliases/UndefinedInitialDataInfiniteOptions" + }, + { + "label": "Types / UndefinedInitialDataOptions", + "to": "framework/react/reference/type-aliases/UndefinedInitialDataOptions" + }, + { + "label": "Types / UnusedSkipTokenInfiniteOptions", + "to": "framework/react/reference/type-aliases/UnusedSkipTokenInfiniteOptions" + }, + { + "label": "Types / UnusedSkipTokenOptions", + "to": "framework/react/reference/type-aliases/UnusedSkipTokenOptions" + }, + { + "label": "Types / UseBaseMutationResult", + "to": "framework/react/reference/type-aliases/UseBaseMutationResult" + }, + { + "label": "Types / UseBaseQueryResult", + "to": "framework/react/reference/type-aliases/UseBaseQueryResult" + }, + { + "label": "Types / UseInfiniteQueryResult", + "to": "framework/react/reference/type-aliases/UseInfiniteQueryResult" + }, + { + "label": "Types / UseMutateAsyncFunction", + "to": "framework/react/reference/type-aliases/UseMutateAsyncFunction" + }, + { + "label": "Types / UseMutateFunction", + "to": "framework/react/reference/type-aliases/UseMutateFunction" + }, + { + "label": "Types / UseMutationResult", + "to": "framework/react/reference/type-aliases/UseMutationResult" + }, + { + "label": "Types / UsePrefetchInfiniteQueryOptions", + "to": "framework/react/reference/type-aliases/UsePrefetchInfiniteQueryOptions" + }, + { + "label": "Types / UsePrefetchQueryOptions", + "to": "framework/react/reference/type-aliases/UsePrefetchQueryOptions" + }, + { + "label": "Types / UseQueryResult", + "to": "framework/react/reference/type-aliases/UseQueryResult" + }, + { + "label": "Types / UseSuspenseInfiniteQueryResult", + "to": "framework/react/reference/type-aliases/UseSuspenseInfiniteQueryResult" + }, + { + "label": "Types / UseSuspenseQueryResult", + "to": "framework/react/reference/type-aliases/UseSuspenseQueryResult" + }, + { + "label": "Variables / IsRestoringProvider", + "to": "framework/react/reference/variables/IsRestoringProvider" + }, + { + "label": "Variables / QueryClientContext", + "to": "framework/react/reference/variables/QueryClientContext" } ] }, diff --git a/docs/framework/react/guides/caching.md b/docs/framework/react/guides/caching.md index eed24ea2edd..bd76a1b7195 100644 --- a/docs/framework/react/guides/caching.md +++ b/docs/framework/react/guides/caching.md @@ -23,7 +23,7 @@ Let's assume we are using the default `gcTime` of **5 minutes** and the default - A second instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts elsewhere. - Since the cache already has data for the `['todos']` key from the first query, that data is immediately returned from the cache. - The new instance triggers a new network request using its query function. - - Note that regardless of whether both `fetchTodos` query functions are identical or not, both queries' [`status`](../reference/useQuery.md) are updated (including `isFetching`, `isPending`, and other related values) because they have the same query key. + - Note that regardless of whether both `fetchTodos` query functions are identical or not, both queries' [`status`](../reference/functions/useQuery.md) are updated (including `isFetching`, `isPending`, and other related values) because they have the same query key. - When the request completes successfully, the cache's data under the `['todos']` key is updated with the new data, and both instances are updated with the new data. - Both instances of the `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` query are unmounted and no longer in use. - Since there are no more active instances of this query, a garbage collection timeout is set using `gcTime` to delete and garbage collect the query (defaults to **5 minutes**). diff --git a/docs/framework/react/guides/migrating-to-react-query-3.md b/docs/framework/react/guides/migrating-to-react-query-3.md index 5f22f64de49..73298acf106 100644 --- a/docs/framework/react/guides/migrating-to-react-query-3.md +++ b/docs/framework/react/guides/migrating-to-react-query-3.md @@ -103,8 +103,8 @@ try { Together, these provide the same experience as before, but with added control to choose which component trees you want to reset. For more information, see: -- [QueryErrorResetBoundary](../reference/QueryErrorResetBoundary.md) -- [useQueryErrorResetBoundary](../reference/useQueryErrorResetBoundary.md) +- [QueryErrorResetBoundary](../reference/functions/QueryErrorResetBoundary.md) +- [useQueryErrorResetBoundary](../reference/functions/useQueryErrorResetBoundary.md) ### `QueryCache.getQuery()` has been replaced by `QueryCache.find()`. diff --git a/docs/framework/react/guides/migrating-to-v5.md b/docs/framework/react/guides/migrating-to-v5.md index 341e26df462..f46d4b6a12d 100644 --- a/docs/framework/react/guides/migrating-to-v5.md +++ b/docs/framework/react/guides/migrating-to-v5.md @@ -521,7 +521,7 @@ Infinite Queries can be prefetched like regular Queries. Per default, only the f ### New `combine` option for `useQueries` -See the [useQueries docs](../reference/useQueries.md#combine) for more details. +See the [useQueries docs](../reference/functions/useQueries.md#combine) for more details. ### Experimental `fine grained storage persister` diff --git a/docs/framework/react/guides/parallel-queries.md b/docs/framework/react/guides/parallel-queries.md index 83e70f46f2b..b842aac40cd 100644 --- a/docs/framework/react/guides/parallel-queries.md +++ b/docs/framework/react/guides/parallel-queries.md @@ -58,6 +58,6 @@ function App({ users }) { [//]: # 'Example2' [//]: # 'TypeScriptSelect' -> When using TypeScript, an inline `select` written on a query object passed to `useQueries` can't infer its `data` argument from that same object's `queryFn` — it falls back to `unknown`. Annotate the `select` parameter explicitly, or define the query with the [`queryOptions`](../reference/queryOptions.md) helper, to keep type inference. See [this known limitation](https://github.com/TanStack/query/issues/6556). +> When using TypeScript, an inline `select` written on a query object passed to `useQueries` can't infer its `data` argument from that same object's `queryFn` — it falls back to `unknown`. Annotate the `select` parameter explicitly, or define the query with the [`queryOptions`](../reference/functions/queryOptions.md) helper, to keep type inference. See [this known limitation](https://github.com/TanStack/query/issues/6556). [//]: # 'TypeScriptSelect' diff --git a/docs/framework/react/guides/prefetching.md b/docs/framework/react/guides/prefetching.md index 0ee3e6e1b49..5b5260838dc 100644 --- a/docs/framework/react/guides/prefetching.md +++ b/docs/framework/react/guides/prefetching.md @@ -212,7 +212,7 @@ This starts fetching `'article-comments'` immediately and flattens the waterfall [//]: # 'Suspense' -If you want to prefetch together with Suspense, you will have to do things a bit differently. You can't use `useSuspenseQueries` to prefetch, since the prefetch would block the component from rendering. You also can not use `useQuery` for the prefetch, because that wouldn't start the prefetch until after suspenseful query had resolved. For this scenario, you can use the [`usePrefetchQuery`](../reference/usePrefetchQuery.md) or the [`usePrefetchInfiniteQuery`](../reference/usePrefetchInfiniteQuery.md) hooks available in the library. +If you want to prefetch together with Suspense, you will have to do things a bit differently. You can't use `useSuspenseQueries` to prefetch, since the prefetch would block the component from rendering. You also can not use `useQuery` for the prefetch, because that wouldn't start the prefetch until after suspenseful query had resolved. For this scenario, you can use the [`usePrefetchQuery`](../reference/functions/usePrefetchQuery.md) or the [`usePrefetchInfiniteQuery`](../reference/functions/usePrefetchInfiniteQuery.md) hooks available in the library. You can now use `useSuspenseQuery` in the component that actually needs the data. You _might_ want to wrap this later component in its own `` boundary so the "secondary" query we are prefetching does not block rendering of the "primary" data. diff --git a/docs/framework/react/guides/query-options.md b/docs/framework/react/guides/query-options.md index c994cc0d9be..da265975144 100644 --- a/docs/framework/react/guides/query-options.md +++ b/docs/framework/react/guides/query-options.md @@ -31,7 +31,7 @@ queryClient.setQueryData(groupOptions(42).queryKey, newGroups) [//]: # 'Example1' -For Infinite Queries, a separate [`infiniteQueryOptions`](../reference/infiniteQueryOptions.md) helper is available. +For Infinite Queries, a separate [`infiniteQueryOptions`](../reference/functions/infiniteQueryOptions.md) helper is available. [//]: # 'SelectDescription' diff --git a/docs/framework/react/guides/ssr.md b/docs/framework/react/guides/ssr.md index cddaebb42fd..0b6da29d9bc 100644 --- a/docs/framework/react/guides/ssr.md +++ b/docs/framework/react/guides/ssr.md @@ -552,7 +552,7 @@ In case you are creating the `QueryClient` for every request, React Query create On the server, `gcTime` defaults to `Infinity` which disables manual garbage collection and will automatically clear memory once a request has finished. If you are explicitly setting a non-Infinity `gcTime` then you will be responsible for clearing the cache early. -Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/hydration.md#hydrationboundary) places necessary data into the cache for rendering, but if the garbage collector removes the data before the rendering completes, issues may arise. If you require a shorter `gcTime`, we recommend setting it to `2 * 1000` to allow sufficient time for the app to reference the data. +Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/functions/HydrationBoundary.md) places necessary data into the cache for rendering, but if the garbage collector removes the data before the rendering completes, issues may arise. If you require a shorter `gcTime`, we recommend setting it to `2 * 1000` to allow sufficient time for the app to reference the data. To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../../../reference/QueryClient.md#queryclientclear) after the request is handled and dehydrated state has been sent to the client. diff --git a/docs/framework/react/guides/suspense.md b/docs/framework/react/guides/suspense.md index 2c84c5ba308..a1b9ceb6a3d 100644 --- a/docs/framework/react/guides/suspense.md +++ b/docs/framework/react/guides/suspense.md @@ -5,9 +5,9 @@ title: Suspense React Query can also be used with React's Suspense for Data Fetching APIs. For this, we have dedicated hooks: -- [useSuspenseQuery](../reference/useSuspenseQuery.md) -- [useSuspenseInfiniteQuery](../reference/useSuspenseInfiniteQuery.md) -- [useSuspenseQueries](../reference/useSuspenseQueries.md) +- [useSuspenseQuery](../reference/functions/useSuspenseQuery.md) +- [useSuspenseInfiniteQuery](../reference/functions/useSuspenseInfiniteQuery.md) +- [useSuspenseQueries](../reference/functions/useSuspenseQueries.md) When using suspense mode, `status` states and `error` objects are not needed and are then replaced by usage of the `React.Suspense` component (including the use of the `fallback` prop and React error boundaries for catching errors). Please read the [Resetting Error Boundaries](#resetting-error-boundaries) and look at the [Suspense Example](../examples/suspense) for more information on how to set up suspense mode. diff --git a/docs/framework/react/overview.md b/docs/framework/react/overview.md index 6c9a3f0dacd..d65e33cbddc 100644 --- a/docs/framework/react/overview.md +++ b/docs/framework/react/overview.md @@ -96,7 +96,7 @@ function Example() { ## You talked me into it, so what now? - Consider taking the official [TanStack Query Course](https://query.gg?s=tanstack) (or buying it for your whole team!) -- Learn TanStack Query at your own pace with our amazingly thorough [Walkthrough Guide](./installation.md) and [API Reference](./reference/useQuery.md) +- Learn TanStack Query at your own pace with our amazingly thorough [Walkthrough Guide](./installation.md) and [API Reference](./reference/index.md) - See the Article [Why You Want React Query](https://tkdodo.eu/blog/why-you-want-react-query). [//]: # 'Materials' diff --git a/docs/framework/react/plugins/persistQueryClient.md b/docs/framework/react/plugins/persistQueryClient.md index d5562e65d02..2dc8a86e187 100644 --- a/docs/framework/react/plugins/persistQueryClient.md +++ b/docs/framework/react/plugins/persistQueryClient.md @@ -58,7 +58,7 @@ the persister `removeClient()` is called and the cache is immediately discarded. ### `persistQueryClientSave` -- Your query/mutation are [`dehydrated`](../reference/hydration.md#dehydrate) and stored by the persister you provided. +- Your query/mutation are `dehydrated` and stored by the persister you provided. - `createSyncStoragePersister` and `createAsyncStoragePersister` throttle this action to happen at most every 1 second to save on potentially expensive writes. Review their documentation to see how to customize their throttle timing. You can use this to explicitly persist the cache at the moment(s) you choose. @@ -90,7 +90,7 @@ persistQueryClientSubscribe({ ### `persistQueryClientRestore` -- Attempts to [`hydrate`](../reference/hydration.md#hydrate) a previously persisted dehydrated query/mutation cache from the persister back into the query cache of the passed query client. +- Attempts to `hydrate` a previously persisted dehydrated query/mutation cache from the persister back into the query cache of the passed query client. - If a cache is found that is older than the `maxAge` (which by default is 24 hours), it will be discarded. This timing can be customized as you see fit. You can use this to restore the cache at moment(s) you choose. @@ -180,7 +180,7 @@ ReactDOM.createRoot(rootElement).render() ### PersistQueryClientProvider -For this use-case, you can use the `PersistQueryClientProvider`. It will make sure to subscribe / unsubscribe correctly according to the React component lifecycle, and it will also make sure that queries will not start fetching while we are still restoring. Queries will still render though, they will just be put into `fetchingState: 'idle'` until data has been restored. Then, they will refetch unless the restored data is _fresh_ enough, and _initialData_ will also be respected. It can be used _instead of_ the normal [QueryClientProvider](../reference/QueryClientProvider.md): +For this use-case, you can use the `PersistQueryClientProvider`. It will make sure to subscribe / unsubscribe correctly according to the React component lifecycle, and it will also make sure that queries will not start fetching while we are still restoring. Queries will still render though, they will just be put into `fetchingState: 'idle'` until data has been restored. Then, they will refetch unless the restored data is _fresh_ enough, and _initialData_ will also be respected. It can be used _instead of_ the normal [QueryClientProvider](../reference/functions/QueryClientProvider.md): ```tsx import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' @@ -210,7 +210,7 @@ ReactDOM.createRoot(rootElement).render( #### Props -`PersistQueryClientProvider` takes the same props as [QueryClientProvider](../reference/QueryClientProvider.md), and additionally: +`PersistQueryClientProvider` takes the same props as [QueryClientProvider](../reference/functions/QueryClientProvider.md), and additionally: - `persistOptions: PersistQueryClientOptions` - all [options](#options) you can pass to [persistQueryClient](#persistqueryclient) minus the QueryClient itself diff --git a/docs/framework/react/reference/QueryClientProvider.md b/docs/framework/react/reference/QueryClientProvider.md deleted file mode 100644 index 08d6d9ec321..00000000000 --- a/docs/framework/react/reference/QueryClientProvider.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -id: QueryClientProvider -title: QueryClientProvider ---- - -Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application: - -```tsx -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' - -const queryClient = new QueryClient() - -function App() { - return ... -} -``` - -**Options** - -- `client: QueryClient` - - **Required** - - the QueryClient instance to provide diff --git a/docs/framework/react/reference/QueryErrorResetBoundary.md b/docs/framework/react/reference/QueryErrorResetBoundary.md deleted file mode 100644 index d1182bab5b9..00000000000 --- a/docs/framework/react/reference/QueryErrorResetBoundary.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -id: QueryErrorResetBoundary -title: QueryErrorResetBoundary ---- - -When using **suspense** or **throwOnError** in your queries, you need a way to let queries know that you want to try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can reset any query errors within the boundaries of the component. - -```tsx -import { QueryErrorResetBoundary } from '@tanstack/react-query' -import { ErrorBoundary } from 'react-error-boundary' - -const App = () => ( - - {({ reset }) => ( - ( -
- There was an error! - -
- )} - > - -
- )} -
-) -``` diff --git a/docs/framework/react/reference/functions/HydrationBoundary.md b/docs/framework/react/reference/functions/HydrationBoundary.md new file mode 100644 index 00000000000..e00f10b5ba1 --- /dev/null +++ b/docs/framework/react/reference/functions/HydrationBoundary.md @@ -0,0 +1,62 @@ +--- +id: HydrationBoundary +title: HydrationBoundary +--- + +```ts +function HydrationBoundary(__namedParameters): ReactElement>; +``` + +Defined in: [react-query/src/HydrationBoundary.tsx:86](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L86) + +`HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by +`useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on +update timestamp. + +Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + +## Parameters + +### \_\_namedParameters + +[`HydrationBoundaryProps`](../interfaces/HydrationBoundaryProps.md) + +## Returns + +`ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> + +The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the +cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect +after commit. + +## Examples + +```tsx +import { HydrationBoundary } from '@tanstack/react-query' + +function App() { + return ... +} +``` + +Server-side prefetch handed off to the client via `dehydrate`: +```tsx +import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query' + +async function ServerComponent() { + const queryClient = getQueryClient() + + await queryClient + .query({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + .catch(noop) + + return ( + + + + ) +} +``` diff --git a/docs/framework/react/reference/functions/QueryClientProvider.md b/docs/framework/react/reference/functions/QueryClientProvider.md new file mode 100644 index 00000000000..1ca10076ffc --- /dev/null +++ b/docs/framework/react/reference/functions/QueryClientProvider.md @@ -0,0 +1,39 @@ +--- +id: QueryClientProvider +title: QueryClientProvider +--- + +```ts +function QueryClientProvider(__namedParameters): Element; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:70](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L70) + +Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also +calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to +focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or +comes back online). + +## Parameters + +### \_\_namedParameters + +[`QueryClientProviderProps`](../type-aliases/QueryClientProviderProps.md) + +## Returns + +`Element` + +The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + +## Example + +```tsx +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' + +const queryClient = new QueryClient() + +function App() { + return ... +} +``` diff --git a/docs/framework/react/reference/functions/QueryErrorResetBoundary.md b/docs/framework/react/reference/functions/QueryErrorResetBoundary.md new file mode 100644 index 00000000000..111ca3711c3 --- /dev/null +++ b/docs/framework/react/reference/functions/QueryErrorResetBoundary.md @@ -0,0 +1,54 @@ +--- +id: QueryErrorResetBoundary +title: QueryErrorResetBoundary +--- + +```ts +function QueryErrorResetBoundary(__namedParameters): Element; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:136](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L136) + +When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to +try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can +reset any query errors within the boundaries of the component. + +## Parameters + +### \_\_namedParameters + +[`QueryErrorResetBoundaryProps`](../interfaces/QueryErrorResetBoundaryProps.md) + +## Returns + +`Element` + +The `children`, rendered as-is, or called with the boundary's QueryErrorResetBoundaryValue +if `children` is a function. + +## Example + +```tsx +import { ErrorBoundary } from 'react-error-boundary' +import { QueryErrorResetBoundary } from '@tanstack/react-query' + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + +
+ )} +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/infiniteQueryOptions.md b/docs/framework/react/reference/functions/infiniteQueryOptions.md new file mode 100644 index 00000000000..f78a3746c8d --- /dev/null +++ b/docs/framework/react/reference/functions/infiniteQueryOptions.md @@ -0,0 +1,256 @@ +--- +id: infiniteQueryOptions +title: infiniteQueryOptions +--- + +## Call Signature + +```ts +function infiniteQueryOptions(options): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:170](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L170) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. + +This overload is selected when `initialData` is set. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`, with `initialData` set. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### See + +[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + +### Remarks + +See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages, from a button click or +automatically as the user scrolls. + +### Example + +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query' + +export const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + initialData: { pages: [], pageParams: [] }, +}) + +function Projects() { + // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + // list stays visible alongside the error. + const { data, isError, error } = useInfiniteQuery(projectsOptions) + + return ( +
+ {isError ? Error: {error.message} : null} +
    + {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} +
+
+ ) +} +``` + +## Call Signature + +```ts +function infiniteQueryOptions(options): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag, TError>; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:232](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L232) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`UnusedSkipTokenInfiniteOptions`](../type-aliases/UnusedSkipTokenInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UnusedSkipTokenInfiniteOptions](../type-aliases/UnusedSkipTokenInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### Remarks + +See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages, from a button click or +automatically as the user scrolls. + +### Example + +A parameterized factory, so the same options object can be reused per `postId`: +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query' + +export const commentsOptions = (postId: string) => + infiniteQueryOptions({ + queryKey: ['post', postId, 'comments'], + queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + +function Comments({ postId }: { postId: string }) { + const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( +
    + {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} +
+ ) +} +``` + +### See + +[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + +## Call Signature + +```ts +function infiniteQueryOptions(options): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:294](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L294) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### Remarks + +See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages (from a button click or +automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + +### Example + +A parameterized factory, so the same options object can be reused per `postId`: +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query' + +export const commentsOptions = (postId: string) => + infiniteQueryOptions({ + queryKey: ['post', postId, 'comments'], + queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + +function Comments({ postId }: { postId: string }) { + const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( +
    + {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} +
+ ) +} +``` + +### See + +[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. diff --git a/docs/framework/react/reference/functions/mutationOptions.md b/docs/framework/react/reference/functions/mutationOptions.md new file mode 100644 index 00000000000..b25bfdb0c3d --- /dev/null +++ b/docs/framework/react/reference/functions/mutationOptions.md @@ -0,0 +1,143 @@ +--- +id: mutationOptions +title: mutationOptions +--- + +## Call Signature + +```ts +function mutationOptions(options): WithRequired, "mutationKey">; +``` + +Defined in: [react-query/src/mutationOptions.ts:33](https://github.com/TanStack/query/blob/main/packages/react-query/src/mutationOptions.ts#L33) + +You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A +`mutationKey` is required on this overload so the mutation can be looked up later, e.g. with +`useMutationState`. + +### Type Parameters + +#### TData + +`TData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TVariables + +`TVariables` = `void` + +#### TOnMutateResult + +`TOnMutateResult` = `unknown` + +### Parameters + +#### options + +`WithRequired`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The mutation options to use, identical to what you'd pass to `useMutation`, with a +required `mutationKey`. + +### Returns + +`WithRequired`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + +### See + +[useMutation](useMutation.md) to run the mutation these options describe. + +### Example + +Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: +```tsx +import { mutationOptions, useMutationState } from '@tanstack/react-query' + +const createPostOptions = mutationOptions({ + mutationKey: ['posts', 'create'], + mutationFn: createPost, +}) + +function SavingIndicator() { + const isCreatingPost = useMutationState({ + filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + }).length > 0 + + return isCreatingPost ? Saving… : null +} +``` + +## Call Signature + +```ts +function mutationOptions(options): Omit, "mutationKey">; +``` + +Defined in: [react-query/src/mutationOptions.ts:74](https://github.com/TanStack/query/blob/main/packages/react-query/src/mutationOptions.ts#L74) + +You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No +`mutationKey` is required on this overload — use this when you don't need to look the mutation up later +(e.g. with `useMutationState`). + +### Type Parameters + +#### TData + +`TData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TVariables + +`TVariables` = `void` + +#### TOnMutateResult + +`TOnMutateResult` = `unknown` + +### Parameters + +#### options + +`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The mutation options to use, identical to what you'd pass to `useMutation`, without a +`mutationKey`. + +### Returns + +`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + +### See + +[useMutation](useMutation.md) to run the mutation these options describe. + +### Remarks + +Without a `mutationKey`, the mutation can't be targeted via a `mutationKey` filter in +`useMutationState` — it can still be observed through other filters, such as `status` — see the other +overload's example for that. + +### Example + +```tsx +import { mutationOptions, useMutation } from '@tanstack/react-query' + +export const createPostOptions = mutationOptions({ + mutationFn: createPost, +}) + +function CreatePost() { + const mutation = useMutation(createPostOptions) + return +} +``` diff --git a/docs/framework/react/reference/functions/queryOptions.md b/docs/framework/react/reference/functions/queryOptions.md new file mode 100644 index 00000000000..3b79ae5067a --- /dev/null +++ b/docs/framework/react/reference/functions/queryOptions.md @@ -0,0 +1,243 @@ +--- +id: queryOptions +title: queryOptions +--- + +## Call Signature + +```ts +function queryOptions(options): Omit, "queryFn"> & object & QueryKeyWithDataTag; +``` + +Defined in: [react-query/src/queryOptions.ts:142](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L142) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. + +This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`, with `initialData` set. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### See + + - [useQuery](useQuery.md) to run a query with these options. + - [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + +### Example + +```tsx +import { queryOptions, useQuery } from '@tanstack/react-query' + +export const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, + initialData: [], +}) + +function Posts() { + // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + // so the list stays visible alongside the error. + const { data, isError, error } = useQuery(postsOptions) + + return ( +
+ {isError ? Error: {error.message} : null} +
    + {data.map((post) =>
  • {post.title}
  • )} +
+
+ ) +} +``` + +## Call Signature + +```ts +function queryOptions(options): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag; +``` + +Defined in: [react-query/src/queryOptions.ts:183](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L183) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`UnusedSkipTokenOptions`](../type-aliases/UnusedSkipTokenOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UnusedSkipTokenOptions](../type-aliases/UnusedSkipTokenOptions.md) to use — everything you can pass to `useQuery`. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### See + + - [useQuery](useQuery.md) to run a query with these options. + - [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + +### Example + +A parameterized factory, so the same options object can be reused per `id`: +```tsx +import { queryOptions, useQuery } from '@tanstack/react-query' + +export const postOptions = (id: string) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function Post({ id }: { id: string }) { + const { data, isPending, isError, error } = useQuery(postOptions(id)) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return

{data.title}

+} +``` + +## Call Signature + +```ts +function queryOptions(options): UseQueryOptions & object & QueryKeyWithDataTag; +``` + +Defined in: [react-query/src/queryOptions.ts:247](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L247) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`. + +### Returns + +The same options object, typed so that `queryKey` carries the inferred data type. + +### See + + - [useQuery](useQuery.md) to run a query with these options. + - [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + +### Remarks + +This is the only overload that accepts `queryFn: skipToken`, shown below. + +### Examples + +A parameterized factory, so the same options object can be reused per `id`: +```tsx +import { queryOptions, useQuery } from '@tanstack/react-query' + +export const postOptions = (id: string) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function Post({ id }: { id: string }) { + const { data, isPending, isError, error } = useQuery(postOptions(id)) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return

{data.title}

+} +``` + +A factory that disables the query, type safe, until `postId` is set: +```tsx +import { queryOptions, skipToken, useQuery } from '@tanstack/react-query' + +export const postOptions = (postId: number | undefined) => + queryOptions({ + queryKey: ['post', postId], + queryFn: postId != null ? () => fetchPost(postId) : skipToken, + }) + +function Post({ postId }: { postId: number | undefined }) { + const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + + if (postId == null) return 'Select a post' + if (isLoading) return 'Loading...' + if (isError) return Error: {error.message} + + return

{data?.title}

+} +``` diff --git a/docs/framework/react/reference/functions/useInfiniteQuery.md b/docs/framework/react/reference/functions/useInfiniteQuery.md new file mode 100644 index 00000000000..6656d396b78 --- /dev/null +++ b/docs/framework/react/reference/functions/useInfiniteQuery.md @@ -0,0 +1,446 @@ +--- +id: useInfiniteQuery +title: useInfiniteQuery +--- + +## Call Signature + +```ts +function useInfiniteQuery(options, queryClient?): DefinedUseInfiniteQueryResult; +``` + +Defined in: [react-query/src/useInfiniteQuery.ts:64](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L64) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +This overload is selected when `initialData` is set. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`, with `initialData` set. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Remarks + +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default +refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user +actions, or add conditions like `hasNextPage && !isFetching`. + +### See + +[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + +### Example + +```tsx +import { useInfiniteQuery } from '@tanstack/react-query' + +function Projects() { + // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + // list stays visible alongside the error. + const { data, isError, error } = useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + initialData: { pages: [], pageParams: [] }, + }) + + return ( +
+ {isError ? Error: {error.message} : null} +
    + {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} +
+
+ ) +} +``` + +## Call Signature + +```ts +function useInfiniteQuery(options, queryClient?): UseInfiniteQueryResult; +``` + +Defined in: [react-query/src/useInfiniteQuery.ts:189](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L189) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Remarks + +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default +refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user +actions, or add conditions like `hasNextPage && !isFetching`. + +### See + +[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + +### Examples + +Fetching the next page from a "Load More" button click: +```tsx +import { useInfiniteQuery } from '@tanstack/react-query' + +function Projects() { + const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( + <> +
    + {data.pages.map((page) => + page.projects.map((project) =>
  • {project.name}
  • ), + )} +
+ + + ) +} +``` + +Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a +sentinel element after the list: +```tsx +import { useInfiniteQuery } from '@tanstack/react-query' +import { useEffect, useRef } from 'react' + +function Projects() { + const { + data, + isPending, + isError, + error, + fetchNextPage, + hasNextPage, + isFetching, + isFetchingNextPage, + } = useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + const sentinelRef = useRef(null) + + useEffect(() => { + const sentinel = sentinelRef.current + if (sentinel == null || !hasNextPage || isFetching) return + + const observer = new IntersectionObserver(([entry]) => { + if (entry?.isIntersecting) fetchNextPage() + }) + observer.observe(sentinel) + + return () => observer.disconnect() + }, [hasNextPage, isFetching, fetchNextPage]) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( + <> +
    + {data.pages.map((page) => + page.projects.map((project) =>
  • {project.name}
  • ), + )} +
+
{isFetchingNextPage ? 'Loading more...' : null}
+ + ) +} +``` + +## Call Signature + +```ts +function useInfiniteQuery(options, queryClient?): UseInfiniteQueryResult; +``` + +Defined in: [react-query/src/useInfiniteQuery.ts:344](https://github.com/TanStack/query/blob/main/packages/react-query/src/useInfiniteQuery.ts#L344) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +#### TPageParam + +`TPageParam` = `unknown` + +### Parameters + +#### options + +[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use — everything you can pass to `useInfiniteQuery`. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Remarks + +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default +refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user +actions, or add conditions like `hasNextPage && !isFetching`. + +### See + +[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + +### Examples + +Fetching the next page from a "Load More" button click: +```tsx +import { useInfiniteQuery } from '@tanstack/react-query' + +function Projects() { + const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( + <> +
    + {data.pages.map((page) => + page.projects.map((project) =>
  • {project.name}
  • ), + )} +
+ + + ) +} +``` + +Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a +sentinel element after the list: +```tsx +import { useInfiniteQuery } from '@tanstack/react-query' +import { useEffect, useRef } from 'react' + +function Projects() { + const { + data, + isPending, + isError, + error, + fetchNextPage, + hasNextPage, + isFetching, + isFetchingNextPage, + } = useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + const sentinelRef = useRef(null) + + useEffect(() => { + const sentinel = sentinelRef.current + if (sentinel == null || !hasNextPage || isFetching) return + + const observer = new IntersectionObserver(([entry]) => { + if (entry?.isIntersecting) fetchNextPage() + }) + observer.observe(sentinel) + + return () => observer.disconnect() + }, [hasNextPage, isFetching, fetchNextPage]) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( + <> +
    + {data.pages.map((page) => + page.projects.map((project) =>
  • {project.name}
  • ), + )} +
+
{isFetchingNextPage ? 'Loading more...' : null}
+ + ) +} +``` + +A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` +instead of setting `enabled: false`: +```tsx +import { skipToken, useInfiniteQuery } from '@tanstack/react-query' + +function Comments({ postId }: { postId: string | undefined }) { + // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. + const { data, isLoading, isError, error } = useInfiniteQuery({ + queryKey: ['post', postId, 'comments'], + queryFn: + postId != null + ? ({ pageParam }) => fetchComments(postId, pageParam) + : skipToken, + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + if (postId == null) return 'Select a post' + if (isLoading) return 'Loading...' + if (isError) return Error: {error.message} + + return ( +
    + {data?.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/useIsFetching.md b/docs/framework/react/reference/functions/useIsFetching.md new file mode 100644 index 00000000000..ad5f309bcec --- /dev/null +++ b/docs/framework/react/reference/functions/useIsFetching.md @@ -0,0 +1,61 @@ +--- +id: useIsFetching +title: useIsFetching +--- + +```ts +function useIsFetching(filters?, queryClient?): number; +``` + +Defined in: [react-query/src/useIsFetching.ts:44](https://github.com/TanStack/query/blob/main/packages/react-query/src/useIsFetching.ts#L44) + +`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or +fetching in the background (useful for app-wide loading indicators). + +## Parameters + +### filters? + +`QueryFilters`\ + +The QueryFilters to narrow down the matched queries. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`number` + +Will be the `number` of the queries that your application is currently loading or fetching in the +background. + +## Examples + +```tsx +import { useIsFetching } from '@tanstack/react-query' + +function PostsFetchingIndicator() { + // How many queries matching the posts prefix are fetching? + const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + + return isFetchingPosts ? Refreshing posts... : null +} +``` + +A global loading indicator for any query fetching in the background, not just the ones on screen: +```tsx +import { useIsFetching } from '@tanstack/react-query' + +function GlobalLoadingIndicator() { + const isFetching = useIsFetching() + + return isFetching ? ( +
Queries are fetching in the background...
+ ) : null +} +``` diff --git a/docs/framework/react/reference/functions/useIsMutating.md b/docs/framework/react/reference/functions/useIsMutating.md new file mode 100644 index 00000000000..53f6721837e --- /dev/null +++ b/docs/framework/react/reference/functions/useIsMutating.md @@ -0,0 +1,47 @@ +--- +id: useIsMutating +title: useIsMutating +--- + +```ts +function useIsMutating(filters?, queryClient?): number; +``` + +Defined in: [react-query/src/useMutationState.ts:35](https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutationState.ts#L35) + +`useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching +(useful for app-wide loading indicators). + +## Parameters + +### filters? + +`MutationFilters`\<`unknown`, `Error`, `unknown`, `unknown`\> + +The MutationFilters to narrow down the matched mutations. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`number` + +Will be the `number` of the mutations that your application is currently fetching. + +## Example + +```tsx +import { useIsMutating } from '@tanstack/react-query' + +function PostsMutatingIndicator() { + // How many mutations matching the posts prefix are in progress? + const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + + return isMutatingPosts ? Saving posts... : null +} +``` diff --git a/docs/framework/react/reference/functions/useIsRestoring.md b/docs/framework/react/reference/functions/useIsRestoring.md new file mode 100644 index 00000000000..4d55af9fd93 --- /dev/null +++ b/docs/framework/react/reference/functions/useIsRestoring.md @@ -0,0 +1,20 @@ +--- +id: useIsRestoring +title: useIsRestoring +--- + +```ts +function useIsRestoring(): boolean; +``` + +Defined in: [react-query/src/IsRestoringProvider.ts:13](https://github.com/TanStack/query/blob/main/packages/react-query/src/IsRestoringProvider.ts#L13) + +If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to +check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid +race conditions between the restore and mounting queries. + +## Returns + +`boolean` + +`true` while a persisted client is being restored, `false` otherwise. diff --git a/docs/framework/react/reference/functions/useMutation.md b/docs/framework/react/reference/functions/useMutation.md new file mode 100644 index 00000000000..fb8124eb53d --- /dev/null +++ b/docs/framework/react/reference/functions/useMutation.md @@ -0,0 +1,215 @@ +--- +id: useMutation +title: useMutation +--- + +```ts +function useMutation(options, queryClient?): UseMutationResult; +``` + +Defined in: [react-query/src/useMutation.ts:191](https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutation.ts#L191) + +Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. +`useMutation` is the hook for that. + +## Type Parameters + +### TData + +`TData` = `unknown` + +### TError + +`TError` = `Error` + +### TVariables + +`TVariables` = `void` + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +## Parameters + +### options + +[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> + +The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use — everything you can pass to `useMutation`. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> + +`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second +argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared +mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks +fire only for the latest call you've made, and only while the component is still mounted — unmounting before +the mutation settles removes the subscription and prevents them from firing. + +## See + +[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look +the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). + +## Examples + +```tsx +import { useMutation, useQueryClient } from '@tanstack/react-query' + +function AddTodo() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + return ( + + ) +} +``` + +Rendering the mutation's own state, rather than just firing it off: +```tsx +import { useMutation, useQueryClient } from '@tanstack/react-query' + +function AddTodo() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + return ( +
+ {addMutation.isPending ? ( + 'Adding todo...' + ) : ( + <> + {addMutation.isError ? ( +
An error occurred: {addMutation.error.message}
+ ) : null} + + + )} +
+ ) +} +``` + +Optimistic update via `onMutate`, rolling back on `onError`: +```tsx +import { useMutation, useQueryClient } from '@tanstack/react-query' + +function AddTodo() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onMutate: async (newTodo) => { + await queryClient.cancelQueries({ queryKey: ['todos'] }) + const previousTodos = queryClient.getQueryData>(['todos']) + + queryClient.setQueryData>(['todos'], (old) => [ + ...(old ?? []), + newTodo, + ]) + + // Passed to `onError` as `onMutateResult` if the mutation fails. + return { previousTodos } + }, + onError: (_err, _newTodo, onMutateResult) => { + queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, + }) + + return ( + + ) +} +``` + +Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a +promise per call instead, so you can wait for all of them: +```tsx +import { useMutation, useQueryClient } from '@tanstack/react-query' + +function AddTodos() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + async function handleAddAll(todos: Array) { + try { + await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) + } catch (error) { + console.error('Failed to add todos:', error) + } + } + + return ( + + ) +} +``` + +If some of the mutations above can fail independently of the others, and you want to know which ones +did — rather than losing that information the moment the first one rejects — swap `Promise.all` for +`Promise.allSettled`: +```tsx +import { useMutation, useQueryClient } from '@tanstack/react-query' + +function AddTodos() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + async function handleAddAll(todos: Array) { + const addResults = await Promise.allSettled( + todos.map((todo) => addMutation.mutateAsync(todo)), + ) + + addResults.forEach((addResult, index) => { + if (addResult.status === 'rejected') { + console.error(`Failed to add "${todos[index]}":`, addResult.reason) + } + }) + } + + return ( + + ) +} +``` diff --git a/docs/framework/react/reference/functions/useMutationState.md b/docs/framework/react/reference/functions/useMutationState.md new file mode 100644 index 00000000000..1f02f52e201 --- /dev/null +++ b/docs/framework/react/reference/functions/useMutationState.md @@ -0,0 +1,107 @@ +--- +id: useMutationState +title: useMutationState +--- + +```ts +function useMutationState(options, queryClient?): TResult[]; +``` + +Defined in: [react-query/src/useMutationState.ts:157](https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutationState.ts#L157) + +`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass +`filters` (MutationFilters) to narrow down your mutations, and `select` to transform the mutation +state. + +## Type Parameters + +### TResult + +`TResult` = `MutationState`\<`unknown`, `Error`, `unknown`, `unknown`\> + +### TMutation + +`TMutation` *extends* `Mutation`\<`any`, `any`, `any`, `any`\> = `MutationTypeFromResult`\<`TResult`\> + +## Parameters + +### options + +`MutationStateOptions`\<`TResult`, `TMutation`\> = `{}` + +The `filters` to narrow down matched mutations, and an optional `select` to transform the +mutation state. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`TResult`[] + +Will be an Array of whatever `select` returns for each matching mutation. + +## Examples + +Get all variables of all running mutations: +```tsx +import { useMutationState } from '@tanstack/react-query' + +function PendingPosts() { + const pendingVariables = useMutationState({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, + }) + + return <>{pendingVariables.length} posts saving... +} +``` + +Get all data for specific mutations via the `mutationKey`: +```tsx +import { useMutation, useMutationState } from '@tanstack/react-query' + +const mutationKey = ['posts'] + +function Posts() { + // Some mutation that we want to get the state for + const mutation = useMutation({ + mutationKey, + mutationFn: createPosts, + }) + + const savedPosts = useMutationState({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey, status: 'success' }, + select: (mutation) => mutation.state.data, + }) + + return ( + + ) +} +``` + +Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the +mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the +latest invocation: +```tsx +import { useMutationState } from '@tanstack/react-query' + +function LatestPost() { + const savedPosts = useMutationState({ + filters: { mutationKey: ['posts'], status: 'success' }, + select: (mutation) => mutation.state.data, + }) + + const latestSavedPost = savedPosts[savedPosts.length - 1] + + return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} +} +``` diff --git a/docs/framework/react/reference/functions/usePrefetchInfiniteQuery.md b/docs/framework/react/reference/functions/usePrefetchInfiniteQuery.md new file mode 100644 index 00000000000..5ffc7cc5b9b --- /dev/null +++ b/docs/framework/react/reference/functions/usePrefetchInfiniteQuery.md @@ -0,0 +1,92 @@ +--- +id: usePrefetchInfiniteQuery +title: usePrefetchInfiniteQuery +--- + +```ts +function usePrefetchInfiniteQuery(options, queryClient?): void; +``` + +Defined in: [react-query/src/usePrefetchInfiniteQuery.tsx:56](https://github.com/TanStack/query/blob/main/packages/react-query/src/usePrefetchInfiniteQuery.tsx#L56) + +`usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, +before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass +everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though +`queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless +a default query function has been defined. + +`getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, +as well as pageParam information, and should return a single variable that will be passed to your query +function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + +The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left +over from a previous attempt — so calling this on every render is cheap and won't refetch data that's +already there or already in flight. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +### TError + +`TError` = `Error` + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### TPageParam + +`TPageParam` = `unknown` + +## Parameters + +### options + +[`UsePrefetchInfiniteQueryOptions`](../type-aliases/UsePrefetchInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UsePrefetchInfiniteQueryOptions](../type-aliases/UsePrefetchInfiniteQueryOptions.md) to use — everything you can pass to `queryClient.infiniteQuery`. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`void` + +`void` — nothing is returned. + +## Example + +```tsx +import { Suspense } from 'react' +import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query' + +const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) + +function App() { + // Fire the prefetch during render, before the suspense boundary below. + usePrefetchInfiniteQuery(projectsOptions) + + return ( + Loading projects...}> + + + ) +} +``` diff --git a/docs/framework/react/reference/functions/usePrefetchQuery.md b/docs/framework/react/reference/functions/usePrefetchQuery.md new file mode 100644 index 00000000000..f32a8766ae3 --- /dev/null +++ b/docs/framework/react/reference/functions/usePrefetchQuery.md @@ -0,0 +1,83 @@ +--- +id: usePrefetchQuery +title: usePrefetchQuery +--- + +```ts +function usePrefetchQuery(options, queryClient?): void; +``` + +Defined in: [react-query/src/usePrefetchQuery.tsx:42](https://github.com/TanStack/query/blob/main/packages/react-query/src/usePrefetchQuery.tsx#L42) + +`usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before +a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to +`usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and +`queryFn` is required unless a default query function has been defined. + +The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left +over from a previous attempt — so calling this on every render is cheap and won't refetch data that's +already there or already in flight. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +### TError + +`TError` = `Error` + +### TData + +`TData` = `TQueryFnData` + +### TQueryData + +`TQueryData` = `TQueryFnData` + +### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +## Parameters + +### options + +[`UsePrefetchQueryOptions`](../type-aliases/UsePrefetchQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\> + +The [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`void` + +`void` — nothing is returned. + +## Example + +```tsx +import { Suspense } from 'react' +import { usePrefetchQuery } from '@tanstack/react-query' + +function App() { + // Fire the prefetch during render, before the suspense boundary below. + usePrefetchQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + return ( + Loading posts...}> + + + ) +} +``` diff --git a/docs/framework/react/reference/functions/useQueries.md b/docs/framework/react/reference/functions/useQueries.md new file mode 100644 index 00000000000..81f6a5acb4d --- /dev/null +++ b/docs/framework/react/reference/functions/useQueries.md @@ -0,0 +1,192 @@ +--- +id: useQueries +title: useQueries +--- + +```ts +function useQueries(__namedParameters, queryClient?): TCombinedResult; +``` + +Defined in: [react-query/src/useQueries.ts:354](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQueries.ts#L354) + +The `useQueries` hook can be used to fetch a variable number of queries. + +The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the +`queryClient` option - because the `QueryClient` can be passed in on the top level). + +Having the same query key more than once in the array of query objects may cause some data to be shared +between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired +structure. + +The `combine` option can be used to combine the results of the queries into a single value. The result will +be structurally shared to be as referentially stable as possible. + +## Type Parameters + +### T + +`T` *extends* `any`[] + +### TCombinedResult + +`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseQueryResult\\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseQueryResult\\]\> \} + +## Parameters + +### \_\_namedParameters + +#### combine? + +(`result`) => `TCombinedResult` + +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + +#### queries + + \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>, `GetUseQueryOptionsForUseQueries`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : readonly ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : readonly `unknown`[] *extends* `T` ? `T` : `T` *extends* `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : `UseQueryOptionsForUseQueries`\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\] + \| readonly \[\{ \[K in string \| number \| symbol\]: GetUseQueryOptionsForUseQueries\\]\> \}\] + +An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and +`subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and +`placeholderData` accepts a QueriesPlaceholderDataFunction, which is called with `previousData` +and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + +#### subscribed? + +`boolean` + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +**Default Value** + +```ts +true +``` + +### queryClient? + +`QueryClient` + +Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context +will be used. + +## Returns + +`TCombinedResult` + +The combined result. Without `combine`, this is an array with all the query results, in the same +order as the input. When `combine` is provided, this is the value returned by `combine` instead. + +## Remarks + +The `combine` function only re-runs if it changed referentially, or if any of the query results +changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap +it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to +avoid that. + +Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling +`queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter +of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls +back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate +the `select` parameter explicitly, or define the query with [queryOptions](queryOptions.md), which resolves its types in +a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same +limitation applies to [useSuspenseQueries](useSuspenseQueries.md). + +`placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from +previously rendered queries, because the number of queries can differ between renders. + +## Examples + +```tsx +import { useQueries } from '@tanstack/react-query' + +function Posts({ ids }: { ids: Array }) { + const postQueries = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + staleTime: Infinity, + })), + }) + + return ( +
    + {postQueries.map((query, index) => { + if (query.isPending) return
  • Loading...
  • + if (query.isError) return
  • Error: {query.error.message}
  • + return
  • {query.data.title}
  • + })} +
+ ) +} +``` + +Combining results into a single value: +```tsx +import { useQueries } from '@tanstack/react-query' + +function Posts({ ids }: { ids: Array }) { + const { data, isPending, isError } = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + combine: (postQueries) => { + return { + data: postQueries.map((query) => query.data), + isPending: postQueries.some((query) => query.isPending), + isError: postQueries.some((query) => query.isError), + } + }, + }) + + if (isPending) return 'Loading...' + if (isError) return 'Error loading posts' + + return ( +
    + {data.map((post) => ( +
  • {post?.title}
  • + ))} +
+ ) +} +``` + +Typing `select` via [queryOptions](queryOptions.md). Note that spreading a `queryOptions` result and overriding +`select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is +resolved before it reaches `useQueries`: +```tsx +import { queryOptions, useQueries } from '@tanstack/react-query' + +const postOptions = (id: number) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function PostTitle({ id }: { id: number }) { + const [{ data: broken }] = useQueries({ + queries: [ + { + ...postOptions(id), + // ❌ `data` is `unknown` here + select: (data) => data.title, + }, + ], + }) + + const [{ data: fixed }] = useQueries({ + queries: [ + queryOptions({ + ...postOptions(id), + // ✅ `data` is `Post` + select: (data) => data.title, + }), + ], + }) + + return

{fixed}

+} +``` diff --git a/docs/framework/react/reference/functions/useQuery.md b/docs/framework/react/reference/functions/useQuery.md new file mode 100644 index 00000000000..78a6b27247d --- /dev/null +++ b/docs/framework/react/reference/functions/useQuery.md @@ -0,0 +1,379 @@ +--- +id: useQuery +title: useQuery +--- + +## Call Signature + +```ts +function useQuery(options, queryClient?): DefinedUseQueryResult; +``` + +Defined in: [react-query/src/useQuery.ts:50](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L50) + +This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`, with `initialData` set. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\> + +The current query result, typed so that `status` is `success` — or `error` if a fetch attempt +fails while keeping the existing data (`status` never resolves to `pending` in this overload's type, +since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience. + +### See + +[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`. + +### Example + +```tsx +import { useQuery } from '@tanstack/react-query' + +function Posts() { + // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + // so the list stays visible alongside the error. + const { data, isError, error } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + initialData: [], + }) + + return ( +
+ {isError ? Error: {error.message} : null} +
    + {data.map((post) =>
  • {post.title}
  • )} +
+
+ ) +} +``` + +## Call Signature + +```ts +function useQuery(options, queryClient?): UseQueryResult; +``` + +Defined in: [react-query/src/useQuery.ts:117](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L117) + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\> + +The current query result. `status` is `pending` if there is no cached data to display, `error` if +the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError` +are derived booleans for convenience. + +### See + +[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`. + +### Examples + +```tsx +import { useQuery } from '@tanstack/react-query' + +function Posts() { + const { status, data, error, isFetching } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + if (status === 'pending') return 'Loading...' + if (status === 'error') return Error: {error.message} + + return ( +
+
    + {data.map((post) => ( +
  • {post.title}
  • + ))} +
+
{isFetching ? 'Background Updating...' : ' '}
+
+ ) +} +``` + +The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: +```tsx +import { useQuery } from '@tanstack/react-query' + +function Posts() { + const { isPending, isError, data, error } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return ( +
    + {data.map((post) =>
  • {post.title}
  • )} +
+ ) +} +``` + +## Call Signature + +```ts +function useQuery(options, queryClient?): UseQueryResult; +``` + +Defined in: [react-query/src/useQuery.ts:281](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L281) + +### Type Parameters + +#### TQueryFnData + +`TQueryFnData` = `unknown` + +#### TError + +`TError` = `Error` + +#### TData + +`TData` = `TQueryFnData` + +#### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### Parameters + +#### options + +[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use — everything you can pass to `useQuery`. + +#### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +### Returns + +[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\> + +The current query result. `status` is `pending` if there is no cached data to display, `error` if +the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError` +are derived booleans for convenience. + +### See + +[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`. + +### Examples + +```tsx +import { useQuery } from '@tanstack/react-query' + +function Posts() { + const { status, data, error, isFetching } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + if (status === 'pending') return 'Loading...' + if (status === 'error') return Error: {error.message} + + return ( +
+
    + {data.map((post) => ( +
  • {post.title}
  • + ))} +
+
{isFetching ? 'Background Updating...' : ' '}
+
+ ) +} +``` + +`select` derives whatever `data` a component needs from the cached value, without changing what's +actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: +```tsx +import { useQuery } from '@tanstack/react-query' + +function PostCount() { + const { data, isPending, isError, error } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + select: (posts) => posts.length, + }) + + if (isPending) return 'Loading...' + if (isError) return Error: {error.message} + + return {data} posts +} +``` + +A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the +loading state doesn't show while the query is disabled: +```tsx +import { useQuery } from '@tanstack/react-query' + +function Post({ postId }: { postId: number | undefined }) { + const { data, isLoading, isError, error } = useQuery({ + queryKey: ['post', postId], + queryFn: () => fetchPost(postId!), + enabled: postId != null, + }) + + if (postId == null) return 'Select a post' + if (isLoading) return 'Loading...' + if (isError) return Error: {error.message} + + return

{data?.title}

+} +``` + +The same dependent query, type safe: `skipToken` disables the query without needing the +non-null assertion above, since `queryFn` is only ever called when `postId` is defined. +`refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you +need to trigger the query manually: +```tsx +import { skipToken, useQuery } from '@tanstack/react-query' + +function Post({ postId }: { postId: number | undefined }) { + const { data, isLoading, isError, error } = useQuery({ + queryKey: ['post', postId], + queryFn: postId != null ? () => fetchPost(postId) : skipToken, + }) + + if (postId == null) return 'Select a post' + if (isLoading) return 'Loading...' + if (isError) return Error: {error.message} + + return

{data?.title}

+} +``` + +Seeding a detail query from an already-cached list, to skip the loading state: +```tsx +import { useQuery, useQueryClient } from '@tanstack/react-query' + +function Post({ postId }: { postId: number }) { + const queryClient = useQueryClient() + + const { data, isError, error } = useQuery({ + queryKey: ['post', postId], + queryFn: () => fetchPost(postId), + initialData: () => + queryClient + .getQueryData>(['posts']) + ?.find((post) => post.id === postId), + }) + + if (isError) return Error: {error.message} + + return

{data?.title}

+} +``` + +Paginated data, keeping the previous page's data visible while the next page loads: +```tsx +import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { useState } from 'react' + +function Posts() { + const [page, setPage] = useState(0) + + const { data, isPlaceholderData, isError, error } = useQuery({ + queryKey: ['posts', page], + queryFn: () => fetchPosts(page), + placeholderData: keepPreviousData, + }) + + if (isError) return Error: {error.message} + + return ( +
+
    + {data?.map((post) =>
  • {post.title}
  • )} +
+ +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/useQueryClient.md b/docs/framework/react/reference/functions/useQueryClient.md new file mode 100644 index 00000000000..1ff298c77a2 --- /dev/null +++ b/docs/framework/react/reference/functions/useQueryClient.md @@ -0,0 +1,31 @@ +--- +id: useQueryClient +title: useQueryClient +--- + +```ts +function useQueryClient(queryClient?): QueryClient; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:21](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L21) + +The `useQueryClient` hook returns the current `QueryClient` instance. + +## Parameters + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +`QueryClient` + +The current `QueryClient` instance. + +## Throws + +If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree. diff --git a/docs/framework/react/reference/functions/useQueryErrorResetBoundary.md b/docs/framework/react/reference/functions/useQueryErrorResetBoundary.md new file mode 100644 index 00000000000..9abf9e7a575 --- /dev/null +++ b/docs/framework/react/reference/functions/useQueryErrorResetBoundary.md @@ -0,0 +1,44 @@ +--- +id: useQueryErrorResetBoundary +title: useQueryErrorResetBoundary +--- + +```ts +function useQueryErrorResetBoundary(): QueryErrorResetBoundaryValue; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:76](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L76) + +This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary +defined it will reset them globally. + +## Returns + +`QueryErrorResetBoundaryValue` + +The boundary's QueryErrorResetBoundaryValue. + +## Example + +```tsx +import { ErrorBoundary } from 'react-error-boundary' +import { useQueryErrorResetBoundary } from '@tanstack/react-query' + +function App({ children }: { children: React.ReactNode }) { + const { reset } = useQueryErrorResetBoundary() + + return ( + ( +
+ There was an error! + +
+ )} + > + {children} +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md b/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md new file mode 100644 index 00000000000..f77b6c15050 --- /dev/null +++ b/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md @@ -0,0 +1,140 @@ +--- +id: useSuspenseInfiniteQuery +title: useSuspenseInfiniteQuery +--- + +```ts +function useSuspenseInfiniteQuery(options, queryClient?): UseSuspenseInfiniteQueryResult; +``` + +Defined in: [react-query/src/useSuspenseInfiniteQuery.ts:104](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseInfiniteQuery.ts#L104) + +The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`, +`enabled`, and `placeholderData`. + +Caveat: cancellation does not work. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` + +### TError + +`TError` = `Error` + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`, `unknown`\> + +### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +### TPageParam + +`TPageParam` = `unknown` + +## Parameters + +### options + +[`UseSuspenseInfiniteQueryOptions`](../interfaces/UseSuspenseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) to use — the same options as `useInfiniteQuery`, minus the ones listed above. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +[`UseSuspenseInfiniteQueryResult`](../type-aliases/UseSuspenseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, +`isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set +accordingly). + +## Remarks + +Multiple suspenseful query calls in the same component suspend serially, causing a request +waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until +then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that +imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior, +resulting in outdated data. Make sure to call these functions only in response to user actions, or add +conditions like `hasNextPage && !isFetching`. + +## See + +[useInfiniteQuery](useInfiniteQuery.md) for the non-Suspense version of this hook. + +## Example + +The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is +required around ``. A failed background refetch instead continues to render the cached data. +Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseInfiniteQuery, +} from '@tanstack/react-query' + +function Projects() { + // `data` is guaranteed to be defined here — no `isPending` check needed. + const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + useSuspenseInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + return ( +
+
    + {data.pages.map((page) => + page.projects.map((project) =>
  • {project.name}
  • ), + )} +
+ +
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading projects...}> + + +
+ )} +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/useSuspenseQueries.md b/docs/framework/react/reference/functions/useSuspenseQueries.md new file mode 100644 index 00000000000..fae26cf5207 --- /dev/null +++ b/docs/framework/react/reference/functions/useSuspenseQueries.md @@ -0,0 +1,378 @@ +--- +id: useSuspenseQueries +title: useSuspenseQueries +--- + +## Call Signature + +```ts +function useSuspenseQueries(options, queryClient?): TCombinedResult; +``` + +Defined in: [react-query/src/useSuspenseQueries.ts:349](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseQueries.ts#L349) + +The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` +option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + +### Type Parameters + +#### T + +`T` *extends* `any`[] + +#### TCombinedResult + +`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \} + +### Parameters + +#### options + +The `queries` array to run in Suspense, and an optional `combine` function. + +##### combine? + +(`result`) => `TCombinedResult` + +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + +##### queries + + \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\] + \| readonly \[\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryOptions\\]\> \}\] + +An array with query option objects identical to `useSuspenseQuery`. + +#### queryClient? + +`QueryClient` + +Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context +will be used. + +### Returns + +`TCombinedResult` + +The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be +defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived +flags set accordingly). + +Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone +stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid +this, make sure to set a high enough `staleTime`. Cancellation does not work. + +### Examples + +The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is +required around ``. A failed background refetch instead continues to render the cached data. +Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseQueries, +} from '@tanstack/react-query' + +function Posts({ ids }: { ids: Array }) { + // Every result is guaranteed to be defined — no per-query `isPending` check needed. + const postQueries = useSuspenseQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + }) + + return ( +
    + {postQueries.map((query) => ( +
  • {query.data.title}
  • + ))} +
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading posts...}> + + +
+ )} +
+ ) +} +``` + +Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so +they fetch in parallel rather than suspending one after another: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseQueries, +} from '@tanstack/react-query' + +function Dashboard() { + const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + queries: [ + { queryKey: ['users'], queryFn: fetchUsers }, + { queryKey: ['teams'], queryFn: fetchTeams }, + { queryKey: ['projects'], queryFn: fetchProjects }, + ], + }) + + return ( +
+ + + +
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading dashboard...}> + + +
+ )} +
+ ) +} +``` + +`combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, +not on every individual query update. This overload is the only one that accepts `combine`: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseQueries, +} from '@tanstack/react-query' + +function Refresh() { + const anyFetching = useSuspenseQueries({ + queries: [ + { queryKey: ['users'], queryFn: fetchUsers }, + { queryKey: ['teams'], queryFn: fetchTeams }, + ], + combine: (results) => results.some((result) => result.isFetching), + }) + + return anyFetching ? Refreshing… : null +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading dashboard...}> + + +
+ )} +
+ ) +} +``` + +## Call Signature + +```ts +function useSuspenseQueries(options, queryClient?): TCombinedResult; +``` + +Defined in: [react-query/src/useSuspenseQueries.ts:489](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseQueries.ts#L489) + +The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` +option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + +### Type Parameters + +#### T + +`T` *extends* `any`[] + +#### TCombinedResult + +`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \} + +### Parameters + +#### options + +The `queries` array to run in Suspense, and an optional `combine` function. + +##### combine? + +(`result`) => `TCombinedResult` + +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + +##### queries + +readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...(...)[]`\] *extends* \[...\] ? \[..., ..., ...\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* \[`...Tails[]`\] ? \[`...Tails[]`\] : \[`...(...)[]`\] *extends* ...[] ? ...[] : ...[] : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]\] + +An array with query option objects identical to `useSuspenseQuery`. + +#### queryClient? + +`QueryClient` + +Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context +will be used. + +### Returns + +`TCombinedResult` + +The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be +defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived +flags set accordingly). + +Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone +stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid +this, make sure to set a high enough `staleTime`. Cancellation does not work. + +### Examples + +The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is +required around ``. A failed background refetch instead continues to render the cached data. +Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseQueries, +} from '@tanstack/react-query' + +function Posts({ ids }: { ids: Array }) { + // Every result is guaranteed to be defined — no per-query `isPending` check needed. + const postQueries = useSuspenseQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + }) + + return ( +
    + {postQueries.map((query) => ( +
  • {query.data.title}
  • + ))} +
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading posts...}> + + +
+ )} +
+ ) +} +``` + +Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so +they fetch in parallel rather than suspending one after another: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + QueryErrorResetBoundary, + useSuspenseQueries, +} from '@tanstack/react-query' + +function Dashboard() { + const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + queries: [ + { queryKey: ['users'], queryFn: fetchUsers }, + { queryKey: ['teams'], queryFn: fetchTeams }, + { queryKey: ['projects'], queryFn: fetchProjects }, + ], + }) + + return ( +
+ + + +
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading dashboard...}> + + +
+ )} +
+ ) +} +``` diff --git a/docs/framework/react/reference/functions/useSuspenseQuery.md b/docs/framework/react/reference/functions/useSuspenseQuery.md new file mode 100644 index 00000000000..ad91e596f67 --- /dev/null +++ b/docs/framework/react/reference/functions/useSuspenseQuery.md @@ -0,0 +1,114 @@ +--- +id: useSuspenseQuery +title: useSuspenseQuery +--- + +```ts +function useSuspenseQuery(options, queryClient?): UseSuspenseQueryResult; +``` + +Defined in: [react-query/src/useSuspenseQuery.ts:75](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseQuery.ts#L75) + +The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and +`placeholderData` — and `queryFn` may not be `skipToken`, since Suspense hooks can't render a "disabled" state. + +Caveat: cancellation does not work. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +### TError + +`TError` = `Error` + +### TData + +`TData` = `TQueryFnData` + +### TQueryKey + +`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[] + +## Parameters + +### options + +[`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) to use — the same options as `useQuery`, minus the ones listed above. + +### queryClient? + +`QueryClient` + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + +## Returns + +[`UseSuspenseQueryResult`](../type-aliases/UseSuspenseQueryResult.md)\<`TData`, `TError`\> + +The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData` +is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + +## Remarks + +Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request +waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. +Use [useSuspenseQueries](useSuspenseQueries.md) instead when you have more than one suspenseful query in a component, so they +fetch in parallel. + +## Example + +The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is +required around ``. A failed background refetch instead continues to render the cached data. +Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error: +```tsx +import { Suspense } from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query' + +function Posts() { + // `data` is guaranteed to be defined here — no `isPending` check needed. + const { data, isFetching } = useSuspenseQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + return ( +
+

Posts {isFetching ? '(refreshing...)' : null}

+
    + {data.map((post) => ( +
  • {post.title}
  • + ))} +
+
+ ) +} + +function App() { + return ( + + {({ reset }) => ( + ( +
+ There was an error! + +
+ )} + > + Loading posts...}> + + +
+ )} +
+ ) +} +``` diff --git a/docs/framework/react/reference/hydration.md b/docs/framework/react/reference/hydration.md deleted file mode 100644 index a57f343c16c..00000000000 --- a/docs/framework/react/reference/hydration.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -id: hydration -title: hydration ---- - -## `dehydrate` - -`dehydrate` creates a frozen representation of a `cache` that can later be hydrated with `HydrationBoundary` or `hydrate`. This is useful for passing prefetched queries from server to client or persisting queries to localStorage or other persistent locations. It only includes currently successful queries by default. - -```tsx -import { dehydrate } from '@tanstack/react-query' - -const dehydratedState = dehydrate(queryClient, { - shouldDehydrateQuery, - shouldDehydrateMutation, -}) -``` - -**Options** - -- `client: QueryClient` - - **Required** - - The `queryClient` that should be dehydrated -- `options: DehydrateOptions` - - Optional - - `shouldDehydrateMutation: (mutation: Mutation) => boolean` - - Optional - - Whether to dehydrate mutations. - - The function is called for each mutation in the cache - - Return `true` to include this mutation in dehydration, or `false` otherwise - - Defaults to only including paused mutations - - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateMutation` as part of the return statement - - `shouldDehydrateQuery: (query: Query) => boolean` - - Optional - - Whether to dehydrate queries. - - The function is called for each query in the cache - - Return `true` to include this query in dehydration, or `false` otherwise - - Defaults to only including successful queries - - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateQuery` as part of the return statement - - `serializeData?: (data: any) => any` A function to transform (serialize) data during dehydration. - - `shouldRedactErrors?: (error: unknown) => boolean` - - Optional - - Whether to redact errors from the server during dehydration. - - The function is called for each error in the cache - - Return `true` to redact this error, or `false` otherwise - - Defaults to redacting all errors - -**Returns** - -- `dehydratedState: DehydratedState` - - This includes everything that is needed to hydrate the `queryClient` at a later point - - You **should not** rely on the exact format of this response, it is not part of the public API and can change at any time - - This result is not in serialized form, you need to do that yourself if desired - -### Limitations - -Some storage systems (such as browser [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)) require values to be JSON serializable. If you need to dehydrate values that are not automatically serializable to JSON (like `Error` or `undefined`), you have to serialize them for yourself. Since only successful queries are included per default, to also include `Errors`, you have to provide `shouldDehydrateQuery`, e.g.: - -```tsx -// server -const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors -const serializedState = mySerialize(state) // transform Error instances to objects - -// client -const state = myDeserialize(serializedState) // transform objects back to Error instances -hydrate(client, state) -``` - -## `hydrate` - -`hydrate` adds a previously dehydrated state into a `cache`. - -```tsx -import { hydrate } from '@tanstack/react-query' - -hydrate(queryClient, dehydratedState, options) -``` - -**Options** - -- `client: QueryClient` - - **Required** - - The `queryClient` to hydrate the state into -- `dehydratedState: DehydratedState` - - **Required** - - The state to hydrate into the client -- `options: HydrateOptions` - - Optional - - `defaultOptions: DefaultOptions` - - Optional - - `mutations: MutationOptions` The default mutation options to use for the hydrated mutations. - - `queries: QueryOptions` The default query options to use for the hydrated queries. - - `deserializeData?: (data: any) => any` A function to transform (deserialize) data before it is put into the cache. - - `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -### Limitations - -If the queries you're trying to hydrate already exist in the queryCache, `hydrate` will only overwrite them if the data is newer than the data present in the cache. Otherwise, it will **not** get applied. - -[//]: # 'HydrationBoundary' - -## `HydrationBoundary` - -`HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on update timestamp. - -```tsx -import { HydrationBoundary } from '@tanstack/react-query' - -function App() { - return ... -} -``` - -> Note: Only `queries` can be dehydrated with an `HydrationBoundary`. - -**Options** - -- `state: DehydratedState` - - The state to hydrate -- `options: HydrateOptions` - - Optional - - `defaultOptions: QueryOptions` - - The default query options to use for the hydrated queries. - - Note: unlike `hydrate`, `mutations` cannot be set here. -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -[//]: # 'HydrationBoundary' diff --git a/docs/framework/react/reference/index.md b/docs/framework/react/reference/index.md new file mode 100644 index 00000000000..29afd251300 --- /dev/null +++ b/docs/framework/react/reference/index.md @@ -0,0 +1,81 @@ +--- +id: "@tanstack/react-query" +title: "@tanstack/react-query" +--- + +## Interfaces + +- [HydrationBoundaryProps](interfaces/HydrationBoundaryProps.md) +- [QueryErrorResetBoundaryProps](interfaces/QueryErrorResetBoundaryProps.md) +- [UseBaseQueryOptions](interfaces/UseBaseQueryOptions.md) +- [UseInfiniteQueryOptions](interfaces/UseInfiniteQueryOptions.md) +- [UseMutationOptions](interfaces/UseMutationOptions.md) +- [UseQueryOptions](interfaces/UseQueryOptions.md) +- [UseSuspenseInfiniteQueryOptions](interfaces/UseSuspenseInfiniteQueryOptions.md) +- [UseSuspenseQueryOptions](interfaces/UseSuspenseQueryOptions.md) + +## Type Aliases + +- [AnyUseBaseQueryOptions](type-aliases/AnyUseBaseQueryOptions.md) +- [AnyUseInfiniteQueryOptions](type-aliases/AnyUseInfiniteQueryOptions.md) +- [AnyUseMutationOptions](type-aliases/AnyUseMutationOptions.md) +- [AnyUseQueryOptions](type-aliases/AnyUseQueryOptions.md) +- [AnyUseSuspenseInfiniteQueryOptions](type-aliases/AnyUseSuspenseInfiniteQueryOptions.md) +- [AnyUseSuspenseQueryOptions](type-aliases/AnyUseSuspenseQueryOptions.md) +- [DefinedInitialDataInfiniteOptions](type-aliases/DefinedInitialDataInfiniteOptions.md) +- [DefinedInitialDataOptions](type-aliases/DefinedInitialDataOptions.md) +- [DefinedUseInfiniteQueryResult](type-aliases/DefinedUseInfiniteQueryResult.md) +- [DefinedUseQueryResult](type-aliases/DefinedUseQueryResult.md) +- [QueriesOptions](type-aliases/QueriesOptions.md) +- [QueriesResults](type-aliases/QueriesResults.md) +- [QueryClientProviderProps](type-aliases/QueryClientProviderProps.md) +- [QueryErrorClearResetFunction](type-aliases/QueryErrorClearResetFunction.md) +- [QueryErrorIsResetFunction](type-aliases/QueryErrorIsResetFunction.md) +- [QueryErrorResetBoundaryFunction](type-aliases/QueryErrorResetBoundaryFunction.md) +- [QueryErrorResetFunction](type-aliases/QueryErrorResetFunction.md) +- [SuspenseQueriesOptions](type-aliases/SuspenseQueriesOptions.md) +- [SuspenseQueriesResults](type-aliases/SuspenseQueriesResults.md) +- [UndefinedInitialDataInfiniteOptions](type-aliases/UndefinedInitialDataInfiniteOptions.md) +- [UndefinedInitialDataOptions](type-aliases/UndefinedInitialDataOptions.md) +- [UnusedSkipTokenInfiniteOptions](type-aliases/UnusedSkipTokenInfiniteOptions.md) +- [UnusedSkipTokenOptions](type-aliases/UnusedSkipTokenOptions.md) +- [UseBaseMutationResult](type-aliases/UseBaseMutationResult.md) +- [UseBaseQueryResult](type-aliases/UseBaseQueryResult.md) +- [UseInfiniteQueryResult](type-aliases/UseInfiniteQueryResult.md) +- [UseMutateAsyncFunction](type-aliases/UseMutateAsyncFunction.md) +- [UseMutateFunction](type-aliases/UseMutateFunction.md) +- [UseMutationResult](type-aliases/UseMutationResult.md) +- [UsePrefetchInfiniteQueryOptions](type-aliases/UsePrefetchInfiniteQueryOptions.md) +- [UsePrefetchQueryOptions](type-aliases/UsePrefetchQueryOptions.md) +- [UseQueryResult](type-aliases/UseQueryResult.md) +- [UseSuspenseInfiniteQueryResult](type-aliases/UseSuspenseInfiniteQueryResult.md) +- [UseSuspenseQueryResult](type-aliases/UseSuspenseQueryResult.md) + +## Variables + +- [IsRestoringProvider](variables/IsRestoringProvider.md) +- [QueryClientContext](variables/QueryClientContext.md) + +## Functions + +- [HydrationBoundary](functions/HydrationBoundary.md) +- [infiniteQueryOptions](functions/infiniteQueryOptions.md) +- [mutationOptions](functions/mutationOptions.md) +- [QueryClientProvider](functions/QueryClientProvider.md) +- [QueryErrorResetBoundary](functions/QueryErrorResetBoundary.md) +- [queryOptions](functions/queryOptions.md) +- [useInfiniteQuery](functions/useInfiniteQuery.md) +- [useIsFetching](functions/useIsFetching.md) +- [useIsMutating](functions/useIsMutating.md) +- [useIsRestoring](functions/useIsRestoring.md) +- [useMutation](functions/useMutation.md) +- [useMutationState](functions/useMutationState.md) +- [usePrefetchInfiniteQuery](functions/usePrefetchInfiniteQuery.md) +- [usePrefetchQuery](functions/usePrefetchQuery.md) +- [useQueries](functions/useQueries.md) +- [useQuery](functions/useQuery.md) +- [useQueryClient](functions/useQueryClient.md) +- [useQueryErrorResetBoundary](functions/useQueryErrorResetBoundary.md) +- [useSuspenseInfiniteQuery](functions/useSuspenseInfiniteQuery.md) +- [useSuspenseQueries](functions/useSuspenseQueries.md) +- [useSuspenseQuery](functions/useSuspenseQuery.md) diff --git a/docs/framework/react/reference/infiniteQueryOptions.md b/docs/framework/react/reference/infiniteQueryOptions.md deleted file mode 100644 index 5455c2a440f..00000000000 --- a/docs/framework/react/reference/infiniteQueryOptions.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -id: infiniteQueryOptions -title: infiniteQueryOptions ---- - -```tsx -infiniteQueryOptions({ - queryKey, - ...options, -}) -``` - -**Options** - -You can generally pass everything to `infiniteQueryOptions` that you can also pass to [`useInfiniteQuery`](./useInfiniteQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - -- `queryKey: QueryKey` - - **Required** - - The query key to generate options for. - -See [useInfiniteQuery](./useInfiniteQuery.md) for more information. diff --git a/docs/framework/react/reference/interfaces/HydrationBoundaryProps.md b/docs/framework/react/reference/interfaces/HydrationBoundaryProps.md new file mode 100644 index 00000000000..860db9e12fc --- /dev/null +++ b/docs/framework/react/reference/interfaces/HydrationBoundaryProps.md @@ -0,0 +1,68 @@ +--- +id: HydrationBoundaryProps +title: HydrationBoundaryProps +--- + +Defined in: [react-query/src/HydrationBoundary.tsx:16](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L16) + +The props accepted by `HydrationBoundary`. + +## Properties + +### children? + +```ts +optional children: ReactNode; +``` + +Defined in: [react-query/src/HydrationBoundary.tsx:36](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L36) + +The components to render — always rendered unconditionally, not gated on hydration. New queries are +hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated +data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it +lands. + +*** + +### options? + +```ts +optional options: OmitKeyof & object; +``` + +Defined in: [react-query/src/HydrationBoundary.tsx:24](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L24) + +Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + +#### Type Declaration + +##### defaultOptions? + +```ts +optional defaultOptions: OmitKeyof<{ +}, "mutations">; +``` + +*** + +### queryClient? + +```ts +optional queryClient: QueryClient; +``` + +Defined in: [react-query/src/HydrationBoundary.tsx:40](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L40) + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. + +*** + +### state + +```ts +state: DehydratedState | null | undefined; +``` + +Defined in: [react-query/src/HydrationBoundary.tsx:20](https://github.com/TanStack/query/blob/main/packages/react-query/src/HydrationBoundary.tsx#L20) + +The state to hydrate. diff --git a/docs/framework/react/reference/interfaces/QueryErrorResetBoundaryProps.md b/docs/framework/react/reference/interfaces/QueryErrorResetBoundaryProps.md new file mode 100644 index 00000000000..883b9c00a9f --- /dev/null +++ b/docs/framework/react/reference/interfaces/QueryErrorResetBoundaryProps.md @@ -0,0 +1,23 @@ +--- +id: QueryErrorResetBoundaryProps +title: QueryErrorResetBoundaryProps +--- + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:94](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L94) + +The props accepted by `QueryErrorResetBoundary`. + +## Properties + +### children + +```ts +children: + | ReactNode + | QueryErrorResetBoundaryFunction; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:99](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L99) + +Either a plain node, or a function that receives the boundary's QueryErrorResetBoundaryValue and +returns a node. diff --git a/docs/framework/react/reference/interfaces/UseBaseQueryOptions.md b/docs/framework/react/reference/interfaces/UseBaseQueryOptions.md new file mode 100644 index 00000000000..16f50718bec --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseBaseQueryOptions.md @@ -0,0 +1,65 @@ +--- +id: UseBaseQueryOptions +title: UseBaseQueryOptions +--- + +Defined in: [react-query/src/types.ts:47](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L47) + +The options shared by `useQuery` and `useSuspenseQuery`. Extends QueryObserverOptions from +`@tanstack/query-core` with the `react-query`-specific `subscribed` option. + +## Extends + +- `QueryObserverOptions`\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\> + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no +`select` is used. + +### TQueryData + +`TQueryData` = `TQueryFnData` + +The type of the data actually held in the query cache — the input to `select` and +`placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +## Properties + +### subscribed? + +```ts +optional subscribed: boolean; +``` + +Defined in: [react-query/src/types.ts:65](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L65) + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +#### Default Value + +```ts +true +``` diff --git a/docs/framework/react/reference/interfaces/UseInfiniteQueryOptions.md b/docs/framework/react/reference/interfaces/UseInfiniteQueryOptions.md new file mode 100644 index 00000000000..3ce35ff761b --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseInfiniteQueryOptions.md @@ -0,0 +1,65 @@ +--- +id: UseInfiniteQueryOptions +title: UseInfiniteQueryOptions +--- + +Defined in: [react-query/src/types.ts:238](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L238) + +The options accepted by `useInfiniteQuery`. Extends InfiniteQueryObserverOptions from +`@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which +`react-query` derives from which hook you call rather than exposing as an option). + +## Extends + +- `OmitKeyof`\<`InfiniteQueryObserverOptions`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>, `"suspense"`\> + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs — defaults to `InfiniteData`, +the shape of all fetched pages plus their page params. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. + +## Properties + +### subscribed? + +```ts +optional subscribed: boolean; +``` + +Defined in: [react-query/src/types.ts:259](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L259) + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +#### Default Value + +```ts +true +``` diff --git a/docs/framework/react/reference/interfaces/UseMutationOptions.md b/docs/framework/react/reference/interfaces/UseMutationOptions.md new file mode 100644 index 00000000000..2ae7e55f6a1 --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseMutationOptions.md @@ -0,0 +1,40 @@ +--- +id: UseMutationOptions +title: UseMutationOptions +--- + +Defined in: [react-query/src/types.ts:412](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L412) + +The options accepted by `useMutation`. Same as MutationObserverOptions from `@tanstack/query-core`, +minus the internal `_defaulted` flag. + +## Extends + +- `OmitKeyof`\<`MutationObserverOptions`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"_defaulted"`\> + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type your mutation function resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your mutation function may throw. + +### TVariables + +`TVariables` = `void` + +The type of the variable passed to `mutate`/`mutateAsync`. + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as +their `onMutateResult` parameter — useful for optimistic-update rollback data. diff --git a/docs/framework/react/reference/interfaces/UseQueryOptions.md b/docs/framework/react/reference/interfaces/UseQueryOptions.md new file mode 100644 index 00000000000..2099250b292 --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseQueryOptions.md @@ -0,0 +1,64 @@ +--- +id: UseQueryOptions +title: UseQueryOptions +--- + +Defined in: [react-query/src/types.ts:165](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L165) + +The options accepted by `useQuery`. Same as [UseBaseQueryOptions](UseBaseQueryOptions.md), minus `suspense` (which +`react-query` derives from which hook you call rather than exposing as an option). + +## Extends + +- `OmitKeyof`\<[`UseBaseQueryOptions`](UseBaseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`\>, `"suspense"`\> + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no +`select` is used. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +## Properties + +### subscribed? + +```ts +optional subscribed: boolean; +``` + +Defined in: [react-query/src/types.ts:65](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L65) + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +#### Default Value + +```ts +true +``` + +#### Inherited from + +```ts +OmitKeyof.subscribed +``` diff --git a/docs/framework/react/reference/interfaces/UseSuspenseInfiniteQueryOptions.md b/docs/framework/react/reference/interfaces/UseSuspenseInfiniteQueryOptions.md new file mode 100644 index 00000000000..c3ea5865ffe --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseSuspenseInfiniteQueryOptions.md @@ -0,0 +1,84 @@ +--- +id: UseSuspenseInfiniteQueryOptions +title: UseSuspenseInfiniteQueryOptions +--- + +Defined in: [react-query/src/types.ts:280](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L280) + +The options accepted by `useSuspenseInfiniteQuery`. Same as [UseInfiniteQueryOptions](UseInfiniteQueryOptions.md), minus `enabled`, +`throwOnError`, and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so +those options don't apply. + +## Extends + +- `OmitKeyof`\<[`UseInfiniteQueryOptions`](UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>, `"queryFn"` \| `"enabled"` \| `"throwOnError"` \| `"placeholderData"`\> + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs — defaults to `InfiniteData`, +the shape of all fetched pages plus their page params. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. + +## Properties + +### queryFn? + +```ts +optional queryFn: QueryFunction; +``` + +Defined in: [react-query/src/types.ts:294](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L294) + +`skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function +must always be provided, unless a default query function has been defined. + +*** + +### subscribed? + +```ts +optional subscribed: boolean; +``` + +Defined in: [react-query/src/types.ts:259](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L259) + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +#### Default Value + +```ts +true +``` + +#### Inherited from + +```ts +OmitKeyof.subscribed +``` diff --git a/docs/framework/react/reference/interfaces/UseSuspenseQueryOptions.md b/docs/framework/react/reference/interfaces/UseSuspenseQueryOptions.md new file mode 100644 index 00000000000..f6177722755 --- /dev/null +++ b/docs/framework/react/reference/interfaces/UseSuspenseQueryOptions.md @@ -0,0 +1,78 @@ +--- +id: UseSuspenseQueryOptions +title: UseSuspenseQueryOptions +--- + +Defined in: [react-query/src/types.ts:196](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L196) + +The options accepted by `useSuspenseQuery`. Same as [UseQueryOptions](UseQueryOptions.md), minus `enabled`, `throwOnError`, +and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so those options +don't apply. + +## Extends + +- `OmitKeyof`\<[`UseQueryOptions`](UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>, `"queryFn"` \| `"enabled"` \| `"throwOnError"` \| `"placeholderData"`\> + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no +`select` is used. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +## Properties + +### queryFn? + +```ts +optional queryFn: QueryFunction; +``` + +Defined in: [react-query/src/types.ts:209](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L209) + +`skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function +must always be provided, unless a default query function has been defined. + +*** + +### subscribed? + +```ts +optional subscribed: boolean; +``` + +Defined in: [react-query/src/types.ts:65](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L65) + +Set this to `false` to unsubscribe this observer from updates to the query cache. + +#### Default Value + +```ts +true +``` + +#### Inherited from + +```ts +OmitKeyof.subscribed +``` diff --git a/docs/framework/react/reference/mutationOptions.md b/docs/framework/react/reference/mutationOptions.md deleted file mode 100644 index 0fa145a890f..00000000000 --- a/docs/framework/react/reference/mutationOptions.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -id: mutationOptions -title: mutationOptions ---- - -```tsx -mutationOptions({ - mutationFn, - ...options, -}) -``` - -**Options** - -You can generally pass everything to `mutationOptions` that you can also pass to [`useMutation`](./useMutation.md). diff --git a/docs/framework/react/reference/queryOptions.md b/docs/framework/react/reference/queryOptions.md deleted file mode 100644 index f6f0ac7f2e9..00000000000 --- a/docs/framework/react/reference/queryOptions.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -id: queryOptions -title: queryOptions ---- - -```tsx -queryOptions({ - queryKey, - ...options, -}) -``` - -**Options** - -You can generally pass everything to `queryOptions` that you can also pass to [`useQuery`](./useQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.query`. - -- `queryKey: QueryKey` - - **Required** - - The query key to generate options for. -[//]: # 'Materials' - -## Further reading - -To learn more about `QueryOptions`, have a look at [this article by TkDodo The Query Options API](https://tkdodo.eu/blog/the-query-options-api). - -[//]: # 'Materials' diff --git a/docs/framework/react/reference/type-aliases/AnyUseBaseQueryOptions.md b/docs/framework/react/reference/type-aliases/AnyUseBaseQueryOptions.md new file mode 100644 index 00000000000..947988618e0 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseBaseQueryOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseBaseQueryOptions +title: AnyUseBaseQueryOptions +--- + +```ts +type AnyUseBaseQueryOptions = UseBaseQueryOptions; +``` + +Defined in: [react-query/src/types.ts:28](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L28) + +[UseBaseQueryOptions](../interfaces/UseBaseQueryOptions.md) with all type parameters set to `any`, useful when the specific types aren't +relevant, e.g. when accepting options for any query in a helper function. diff --git a/docs/framework/react/reference/type-aliases/AnyUseInfiniteQueryOptions.md b/docs/framework/react/reference/type-aliases/AnyUseInfiniteQueryOptions.md new file mode 100644 index 00000000000..a38ab02f8cb --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseInfiniteQueryOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseInfiniteQueryOptions +title: AnyUseInfiniteQueryOptions +--- + +```ts +type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions; +``` + +Defined in: [react-query/src/types.ts:219](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L219) + +[UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) with all type parameters set to `any`, useful when the specific types aren't +relevant, e.g. when accepting options for any query in a helper function. diff --git a/docs/framework/react/reference/type-aliases/AnyUseMutationOptions.md b/docs/framework/react/reference/type-aliases/AnyUseMutationOptions.md new file mode 100644 index 00000000000..facf8ea370d --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseMutationOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseMutationOptions +title: AnyUseMutationOptions +--- + +```ts +type AnyUseMutationOptions = UseMutationOptions; +``` + +Defined in: [react-query/src/types.ts:401](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L401) + +[UseMutationOptions](../interfaces/UseMutationOptions.md) with all type parameters set to `any`, useful when the specific types aren't +relevant, e.g. when accepting options for any mutation in a helper function. diff --git a/docs/framework/react/reference/type-aliases/AnyUseQueryOptions.md b/docs/framework/react/reference/type-aliases/AnyUseQueryOptions.md new file mode 100644 index 00000000000..fcfc898f6ed --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseQueryOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseQueryOptions +title: AnyUseQueryOptions +--- + +```ts +type AnyUseQueryOptions = UseQueryOptions; +``` + +Defined in: [react-query/src/types.ts:154](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L154) + +[UseQueryOptions](../interfaces/UseQueryOptions.md) with all type parameters set to `any`, useful when the specific types aren't +relevant, e.g. when accepting options for any query in a helper function. diff --git a/docs/framework/react/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md b/docs/framework/react/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md new file mode 100644 index 00000000000..ea3a18b2716 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseSuspenseInfiniteQueryOptions +title: AnyUseSuspenseInfiniteQueryOptions +--- + +```ts +type AnyUseSuspenseInfiniteQueryOptions = UseSuspenseInfiniteQueryOptions; +``` + +Defined in: [react-query/src/types.ts:266](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L266) + +[UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) with all type parameters set to `any`, useful when the specific types +aren't relevant, e.g. when accepting options for any query in a helper function. diff --git a/docs/framework/react/reference/type-aliases/AnyUseSuspenseQueryOptions.md b/docs/framework/react/reference/type-aliases/AnyUseSuspenseQueryOptions.md new file mode 100644 index 00000000000..150a2781b62 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/AnyUseSuspenseQueryOptions.md @@ -0,0 +1,13 @@ +--- +id: AnyUseSuspenseQueryOptions +title: AnyUseSuspenseQueryOptions +--- + +```ts +type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions; +``` + +Defined in: [react-query/src/types.ts:179](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L179) + +[UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) with all type parameters set to `any`, useful when the specific types aren't +relevant, e.g. when accepting options for any query in a helper function. diff --git a/docs/framework/react/reference/type-aliases/DefinedInitialDataInfiniteOptions.md b/docs/framework/react/reference/type-aliases/DefinedInitialDataInfiniteOptions.md new file mode 100644 index 00000000000..1721394a2ec --- /dev/null +++ b/docs/framework/react/reference/type-aliases/DefinedInitialDataInfiniteOptions.md @@ -0,0 +1,63 @@ +--- +id: DefinedInitialDataInfiniteOptions +title: DefinedInitialDataInfiniteOptions +--- + +```ts +type DefinedInitialDataInfiniteOptions = UseInfiniteQueryOptions & object; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:103](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L103) + +The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is +never `undefined`. + +## Type Declaration + +### initialData + +```ts +initialData: + | NonUndefinedGuard> + | () => NonUndefinedGuard> + | undefined; +``` + +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs — defaults to `InfiniteData`, +the shape of all fetched pages plus their page params. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. diff --git a/docs/framework/react/reference/type-aliases/DefinedInitialDataOptions.md b/docs/framework/react/reference/type-aliases/DefinedInitialDataOptions.md new file mode 100644 index 00000000000..1807607291b --- /dev/null +++ b/docs/framework/react/reference/type-aliases/DefinedInitialDataOptions.md @@ -0,0 +1,65 @@ +--- +id: DefinedInitialDataOptions +title: DefinedInitialDataOptions +--- + +```ts +type DefinedInitialDataOptions = Omit, "queryFn"> & object; +``` + +Defined in: [react-query/src/queryOptions.ts:80](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L80) + +The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never +`undefined`. + +## Type Declaration + +### initialData + +```ts +initialData: + | NonUndefinedGuard +| () => NonUndefinedGuard; +``` + +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + +### queryFn? + +```ts +optional queryFn: QueryFunction; +``` + +Optional here, but omitting it is only safe when no fetch will be attempted — for example with +`enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no +`queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. diff --git a/docs/framework/react/reference/type-aliases/DefinedUseInfiniteQueryResult.md b/docs/framework/react/reference/type-aliases/DefinedUseInfiniteQueryResult.md new file mode 100644 index 00000000000..ee49de8a33a --- /dev/null +++ b/docs/framework/react/reference/type-aliases/DefinedUseInfiniteQueryResult.md @@ -0,0 +1,27 @@ +--- +id: DefinedUseInfiniteQueryResult +title: DefinedUseInfiniteQueryResult +--- + +```ts +type DefinedUseInfiniteQueryResult = DefinedInfiniteQueryObserverResult; +``` + +Defined in: [react-query/src/types.ts:377](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L377) + +The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined`. Re-exports +DefinedInfiniteQueryObserverResult from `@tanstack/query-core`. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/DefinedUseQueryResult.md b/docs/framework/react/reference/type-aliases/DefinedUseQueryResult.md new file mode 100644 index 00000000000..724b88fb8dd --- /dev/null +++ b/docs/framework/react/reference/type-aliases/DefinedUseQueryResult.md @@ -0,0 +1,28 @@ +--- +id: DefinedUseQueryResult +title: DefinedUseQueryResult +--- + +```ts +type DefinedUseQueryResult = DefinedQueryObserverResult; +``` + +Defined in: [react-query/src/types.ts:353](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L353) + +The result of `useQuery` when `initialData` is set, or of `useSuspenseQuery` before the `isPlaceholderData` +omission — `data` is never `undefined`. Re-exports DefinedQueryObserverResult from +`@tanstack/query-core`. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/QueriesOptions.md b/docs/framework/react/reference/type-aliases/QueriesOptions.md new file mode 100644 index 00000000000..9ab4be62e37 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueriesOptions.md @@ -0,0 +1,37 @@ +--- +id: QueriesOptions +title: QueriesOptions +--- + +```ts +type QueriesOptions = TDepth["length"] extends MAXIMUM_DEPTH ? UseQueryOptionsForUseQueries[] : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetUseQueryOptionsForUseQueries] : T extends [infer Head, ...(infer Tails)] ? QueriesOptions<[...Tails], [...TResults, GetUseQueryOptionsForUseQueries], [...TDepth, 1]> : ReadonlyArray extends T ? T : T extends UseQueryOptionsForUseQueries[] ? UseQueryOptionsForUseQueries[] : UseQueryOptionsForUseQueries[]; +``` + +Defined in: [react-query/src/useQueries.ts:156](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQueries.ts#L156) + +The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's +`queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g. +`unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls +back to a single homogeneous options type. + +## Type Parameters + +### T + +`T` *extends* `any`[] + +The type of the `queries` array as written at the call site. + +### TResults + +`TResults` *extends* `any`[] = \[\] + +The internal accumulator that this type builds during recursion. It is not meant +to be set explicitly. + +### TDepth + +`TDepth` *extends* `ReadonlyArray`\<`number`\> = \[\] + +The internal recursion-depth counter, checked against the 20-element limit. It is not +meant to be set explicitly. diff --git a/docs/framework/react/reference/type-aliases/QueriesResults.md b/docs/framework/react/reference/type-aliases/QueriesResults.md new file mode 100644 index 00000000000..c560ce906d6 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueriesResults.md @@ -0,0 +1,37 @@ +--- +id: QueriesResults +title: QueriesResults +--- + +```ts +type QueriesResults = TDepth["length"] extends MAXIMUM_DEPTH ? UseQueryResult[] : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetUseQueryResult] : T extends [infer Head, ...(infer Tails)] ? QueriesResults<[...Tails], [...TResults, GetUseQueryResult], [...TDepth, 1]> : { [K in keyof T]: GetUseQueryResult }; +``` + +Defined in: [react-query/src/useQueries.ts:207](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQueries.ts#L207) + +The result type returned by `useQueries`, when no `combine` is provided. Mirrors [QueriesOptions](QueriesOptions.md): each +tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped +per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a +single homogeneous [UseQueryResult](UseQueryResult.md) type. + +## Type Parameters + +### T + +`T` *extends* `any`[] + +The type of the `queries` array, as inferred by [QueriesOptions](QueriesOptions.md). + +### TResults + +`TResults` *extends* `any`[] = \[\] + +The internal accumulator that this type builds during recursion. It is not meant +to be set explicitly. + +### TDepth + +`TDepth` *extends* `ReadonlyArray`\<`number`\> = \[\] + +The internal recursion-depth counter, checked against the 20-element limit. It is not +meant to be set explicitly. diff --git a/docs/framework/react/reference/type-aliases/QueryClientProviderProps.md b/docs/framework/react/reference/type-aliases/QueryClientProviderProps.md new file mode 100644 index 00000000000..dc1ee2d8bd3 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueryClientProviderProps.md @@ -0,0 +1,38 @@ +--- +id: QueryClientProviderProps +title: QueryClientProviderProps +--- + +```ts +type QueryClientProviderProps = object; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:38](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L38) + +The props accepted by `QueryClientProvider`. + +## Properties + +### children? + +```ts +optional children: React.ReactNode; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:48](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L48) + +The components that get access to the provided `QueryClient`. + +*** + +### client + +```ts +client: QueryClient; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:44](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L44) + +**Required** + +The `QueryClient` instance to provide. diff --git a/docs/framework/react/reference/type-aliases/QueryErrorClearResetFunction.md b/docs/framework/react/reference/type-aliases/QueryErrorClearResetFunction.md new file mode 100644 index 00000000000..73be345b630 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueryErrorClearResetFunction.md @@ -0,0 +1,14 @@ +--- +id: QueryErrorClearResetFunction +title: QueryErrorClearResetFunction +--- + +```ts +type QueryErrorClearResetFunction = () => void; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:7](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L7) + +## Returns + +`void` diff --git a/docs/framework/react/reference/type-aliases/QueryErrorIsResetFunction.md b/docs/framework/react/reference/type-aliases/QueryErrorIsResetFunction.md new file mode 100644 index 00000000000..049ead420e7 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueryErrorIsResetFunction.md @@ -0,0 +1,14 @@ +--- +id: QueryErrorIsResetFunction +title: QueryErrorIsResetFunction +--- + +```ts +type QueryErrorIsResetFunction = () => boolean; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:6](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L6) + +## Returns + +`boolean` diff --git a/docs/framework/react/reference/type-aliases/QueryErrorResetBoundaryFunction.md b/docs/framework/react/reference/type-aliases/QueryErrorResetBoundaryFunction.md new file mode 100644 index 00000000000..df4218127f2 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueryErrorResetBoundaryFunction.md @@ -0,0 +1,26 @@ +--- +id: QueryErrorResetBoundaryFunction +title: QueryErrorResetBoundaryFunction +--- + +```ts +type QueryErrorResetBoundaryFunction = (value) => React.ReactNode; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:87](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L87) + +A render-prop function usable as `children` on `QueryErrorResetBoundary`. + +## Parameters + +### value + +`QueryErrorResetBoundaryValue` + +The boundary's QueryErrorResetBoundaryValue. + +## Returns + +`React.ReactNode` + +The children to render. diff --git a/docs/framework/react/reference/type-aliases/QueryErrorResetFunction.md b/docs/framework/react/reference/type-aliases/QueryErrorResetFunction.md new file mode 100644 index 00000000000..a4bbfd436ec --- /dev/null +++ b/docs/framework/react/reference/type-aliases/QueryErrorResetFunction.md @@ -0,0 +1,14 @@ +--- +id: QueryErrorResetFunction +title: QueryErrorResetFunction +--- + +```ts +type QueryErrorResetFunction = () => void; +``` + +Defined in: [react-query/src/QueryErrorResetBoundary.tsx:5](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryErrorResetBoundary.tsx#L5) + +## Returns + +`void` diff --git a/docs/framework/react/reference/type-aliases/SuspenseQueriesOptions.md b/docs/framework/react/reference/type-aliases/SuspenseQueriesOptions.md new file mode 100644 index 00000000000..213540b5449 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/SuspenseQueriesOptions.md @@ -0,0 +1,37 @@ +--- +id: SuspenseQueriesOptions +title: SuspenseQueriesOptions +--- + +```ts +type SuspenseQueriesOptions = TDepth["length"] extends MAXIMUM_DEPTH ? UseSuspenseQueryOptions[] : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetUseSuspenseQueryOptions] : T extends [infer Head, ...(infer Tails)] ? SuspenseQueriesOptions<[...Tails], [...TResults, GetUseSuspenseQueryOptions], [...TDepth, 1]> : unknown[] extends T ? T : T extends UseSuspenseQueryOptions[] ? UseSuspenseQueryOptions[] : UseSuspenseQueryOptions[]; +``` + +Defined in: [react-query/src/useSuspenseQueries.ts:119](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseQueries.ts#L119) + +The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every +entry's `queryFn`/`select` are inferred individually, up to 20 elements. An opaque array (e.g. `unknown[]`) +is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls back to a +single homogeneous [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) type. + +## Type Parameters + +### T + +`T` *extends* `any`[] + +The type of the `queries` array as written at the call site. + +### TResults + +`TResults` *extends* `any`[] = \[\] + +The internal accumulator that this type builds during recursion. It is not meant +to be set explicitly. + +### TDepth + +`TDepth` *extends* `ReadonlyArray`\<`number`\> = \[\] + +The internal recursion-depth counter, checked against the 20-element limit. It is not +meant to be set explicitly. diff --git a/docs/framework/react/reference/type-aliases/SuspenseQueriesResults.md b/docs/framework/react/reference/type-aliases/SuspenseQueriesResults.md new file mode 100644 index 00000000000..0db1c6f054e --- /dev/null +++ b/docs/framework/react/reference/type-aliases/SuspenseQueriesResults.md @@ -0,0 +1,37 @@ +--- +id: SuspenseQueriesResults +title: SuspenseQueriesResults +--- + +```ts +type SuspenseQueriesResults = TDepth["length"] extends MAXIMUM_DEPTH ? UseSuspenseQueryResult[] : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetUseSuspenseQueryResult] : T extends [infer Head, ...(infer Tails)] ? SuspenseQueriesResults<[...Tails], [...TResults, GetUseSuspenseQueryResult], [...TDepth, 1]> : { [K in keyof T]: GetUseSuspenseQueryResult }; +``` + +Defined in: [react-query/src/useSuspenseQueries.ts:165](https://github.com/TanStack/query/blob/main/packages/react-query/src/useSuspenseQueries.ts#L165) + +The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors +[SuspenseQueriesOptions](SuspenseQueriesOptions.md): each tuple element's result type is inferred individually, up to 20 elements. +A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 +elements does this fall back to a single homogeneous [UseSuspenseQueryResult](UseSuspenseQueryResult.md) type. + +## Type Parameters + +### T + +`T` *extends* `any`[] + +The type of the `queries` array, as inferred by [SuspenseQueriesOptions](SuspenseQueriesOptions.md). + +### TResults + +`TResults` *extends* `any`[] = \[\] + +The internal accumulator that this type builds during recursion. It is not meant +to be set explicitly. + +### TDepth + +`TDepth` *extends* `ReadonlyArray`\<`number`\> = \[\] + +The internal recursion-depth counter, checked against the 20-element limit. It is not +meant to be set explicitly. diff --git a/docs/framework/react/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md b/docs/framework/react/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md new file mode 100644 index 00000000000..a59e75eeb93 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md @@ -0,0 +1,62 @@ +--- +id: UndefinedInitialDataInfiniteOptions +title: UndefinedInitialDataInfiniteOptions +--- + +```ts +type UndefinedInitialDataInfiniteOptions = UseInfiniteQueryOptions & object; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:24](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L24) + +The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data` +may be `undefined` while the query is `pending`. + +## Type Declaration + +### initialData? + +```ts +optional initialData: + | NonUndefinedGuard> +| InitialDataFunction>>; +``` + +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs — defaults to `InfiniteData`, +the shape of all fetched pages plus their page params. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. diff --git a/docs/framework/react/reference/type-aliases/UndefinedInitialDataOptions.md b/docs/framework/react/reference/type-aliases/UndefinedInitialDataOptions.md new file mode 100644 index 00000000000..cfabb5cd25d --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UndefinedInitialDataOptions.md @@ -0,0 +1,55 @@ +--- +id: UndefinedInitialDataOptions +title: UndefinedInitialDataOptions +--- + +```ts +type UndefinedInitialDataOptions = UseQueryOptions & object; +``` + +Defined in: [react-query/src/queryOptions.ts:22](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L22) + +The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be +`undefined` while the query is `pending`. + +## Type Declaration + +### initialData? + +```ts +optional initialData: + | InitialDataFunction> +| NonUndefinedGuard; +``` + +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. diff --git a/docs/framework/react/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md b/docs/framework/react/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md new file mode 100644 index 00000000000..180225a81bf --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md @@ -0,0 +1,60 @@ +--- +id: UnusedSkipTokenInfiniteOptions +title: UnusedSkipTokenInfiniteOptions +--- + +```ts +type UnusedSkipTokenInfiniteOptions = OmitKeyof, "queryFn"> & object; +``` + +Defined in: [react-query/src/infiniteQueryOptions.ts:64](https://github.com/TanStack/query/blob/main/packages/react-query/src/infiniteQueryOptions.ts#L64) + +The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and +`queryFn` is not `skipToken` — same as [UndefinedInitialDataInfiniteOptions](UndefinedInitialDataInfiniteOptions.md), but `queryFn` may not be +`skipToken`. + +## Type Declaration + +### queryFn? + +```ts +optional queryFn: Exclude["queryFn"], SkipToken | undefined>; +``` + +`skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If +you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a +fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been +defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs — defaults to `InfiniteData`, +the shape of all fetched pages plus their page params. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. diff --git a/docs/framework/react/reference/type-aliases/UnusedSkipTokenOptions.md b/docs/framework/react/reference/type-aliases/UnusedSkipTokenOptions.md new file mode 100644 index 00000000000..dee4b40d41a --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UnusedSkipTokenOptions.md @@ -0,0 +1,52 @@ +--- +id: UnusedSkipTokenOptions +title: UnusedSkipTokenOptions +--- + +```ts +type UnusedSkipTokenOptions = OmitKeyof, "queryFn"> & object; +``` + +Defined in: [react-query/src/queryOptions.ts:50](https://github.com/TanStack/query/blob/main/packages/react-query/src/queryOptions.ts#L50) + +The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is +not `skipToken` — same as [UndefinedInitialDataOptions](UndefinedInitialDataOptions.md), but `queryFn` may not be `skipToken`. + +## Type Declaration + +### queryFn? + +```ts +optional queryFn: Exclude["queryFn"], SkipToken | undefined>; +``` + +`skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If +you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a +fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been +defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. diff --git a/docs/framework/react/reference/type-aliases/UseBaseMutationResult.md b/docs/framework/react/reference/type-aliases/UseBaseMutationResult.md new file mode 100644 index 00000000000..f6c7190284c --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseBaseMutationResult.md @@ -0,0 +1,52 @@ +--- +id: UseBaseMutationResult +title: UseBaseMutationResult +--- + +```ts +type UseBaseMutationResult = Override, { + mutate: UseMutateFunction; +}> & object; +``` + +Defined in: [react-query/src/types.ts:471](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L471) + +The result of `useMutation`. Same as MutationObserverResult from `@tanstack/query-core`, with +`mutate` narrowed to the fire-and-forget [UseMutateFunction](UseMutateFunction.md) signature, plus the added `mutateAsync`. + +## Type Declaration + +### mutateAsync + +```ts +mutateAsync: UseMutateAsyncFunction; +``` + +Similar to `mutate`, but returns a promise which can be awaited. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type your mutation function resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your mutation function may throw. + +### TVariables + +`TVariables` = `unknown` + +The type of the variable passed to `mutate`/`mutateAsync`. + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as +their `onMutateResult` parameter — useful for optimistic-update rollback data. diff --git a/docs/framework/react/reference/type-aliases/UseBaseQueryResult.md b/docs/framework/react/reference/type-aliases/UseBaseQueryResult.md new file mode 100644 index 00000000000..fd2e94e6bef --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseBaseQueryResult.md @@ -0,0 +1,28 @@ +--- +id: UseBaseQueryResult +title: UseBaseQueryResult +--- + +```ts +type UseBaseQueryResult = QueryObserverResult; +``` + +Defined in: [react-query/src/types.ts:314](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L314) + +The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is +`pending`. Re-exports QueryObserverResult from `@tanstack/query-core`. `useInfiniteQuery` returns +[UseInfiniteQueryResult](UseInfiniteQueryResult.md) instead. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/UseInfiniteQueryResult.md b/docs/framework/react/reference/type-aliases/UseInfiniteQueryResult.md new file mode 100644 index 00000000000..019bf84cd3c --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseInfiniteQueryResult.md @@ -0,0 +1,27 @@ +--- +id: UseInfiniteQueryResult +title: UseInfiniteQueryResult +--- + +```ts +type UseInfiniteQueryResult = InfiniteQueryObserverResult; +``` + +Defined in: [react-query/src/types.ts:365](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L365) + +The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is +`pending`. Re-exports InfiniteQueryObserverResult from `@tanstack/query-core`. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/UseMutateAsyncFunction.md b/docs/framework/react/reference/type-aliases/UseMutateAsyncFunction.md new file mode 100644 index 00000000000..b190e9e9c5d --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseMutateAsyncFunction.md @@ -0,0 +1,40 @@ +--- +id: UseMutateAsyncFunction +title: UseMutateAsyncFunction +--- + +```ts +type UseMutateAsyncFunction = MutateFunction; +``` + +Defined in: [react-query/src/types.ts:454](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L454) + +The type of `mutateAsync`, as returned by `useMutation`. Similar to [UseMutateFunction](UseMutateFunction.md), but returns a +promise which can be awaited. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type your mutation function resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your mutation function may throw. + +### TVariables + +`TVariables` = `void` + +The type of the variable passed to `mutateAsync`. + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as +their `onMutateResult` parameter — useful for optimistic-update rollback data. diff --git a/docs/framework/react/reference/type-aliases/UseMutateFunction.md b/docs/framework/react/reference/type-aliases/UseMutateFunction.md new file mode 100644 index 00000000000..09312afba8f --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseMutateFunction.md @@ -0,0 +1,51 @@ +--- +id: UseMutateFunction +title: UseMutateFunction +--- + +```ts +type UseMutateFunction = (...args) => void; +``` + +Defined in: [react-query/src/types.ts:433](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L433) + +The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call +`onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced +through the mutation result, not thrown. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type your mutation function resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your mutation function may throw. + +### TVariables + +`TVariables` = `void` + +The type of the variable passed to `mutate`. + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as +their `onMutateResult` parameter — useful for optimistic-update rollback data. + +## Parameters + +### args + +...`Parameters`\<`MutateFunction`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>\> + +## Returns + +`void` diff --git a/docs/framework/react/reference/type-aliases/UseMutationResult.md b/docs/framework/react/reference/type-aliases/UseMutationResult.md new file mode 100644 index 00000000000..6fcc1df853b --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseMutationResult.md @@ -0,0 +1,39 @@ +--- +id: UseMutationResult +title: UseMutationResult +--- + +```ts +type UseMutationResult = UseBaseMutationResult; +``` + +Defined in: [react-query/src/types.ts:500](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L500) + +The result of `useMutation`. Same as [UseBaseMutationResult](UseBaseMutationResult.md). + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type your mutation function resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your mutation function may throw. + +### TVariables + +`TVariables` = `unknown` + +The type of the variable passed to `mutate`/`mutateAsync`. + +### TOnMutateResult + +`TOnMutateResult` = `unknown` + +The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as +their `onMutateResult` parameter — useful for optimistic-update rollback data. diff --git a/docs/framework/react/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md b/docs/framework/react/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md new file mode 100644 index 00000000000..f2dc79b0825 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md @@ -0,0 +1,58 @@ +--- +id: UsePrefetchInfiniteQueryOptions +title: UsePrefetchInfiniteQueryOptions +--- + +```ts +type UsePrefetchInfiniteQueryOptions = DistributiveOmit, "queryFn"> & object; +``` + +Defined in: [react-query/src/types.ts:118](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L118) + +The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, +except `queryFn` is required unless a default query function has been defined. + +## Type Declaration + +### queryFn? + +```ts +optional queryFn: Exclude["queryFn"], SkipToken>; +``` + +`skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, +unless a default query function has been defined. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type of a single page, as your `queryFn` resolves it. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `InfiniteData`\<`TQueryFnData`\> + +The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, +the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this +parameter only matters if you reuse these options elsewhere with `select` applied. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. + +### TPageParam + +`TPageParam` = `unknown` + +The type of the parameter passed to `queryFn` to fetch a given page. diff --git a/docs/framework/react/reference/type-aliases/UsePrefetchQueryOptions.md b/docs/framework/react/reference/type-aliases/UsePrefetchQueryOptions.md new file mode 100644 index 00000000000..2e8ce8ab558 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UsePrefetchQueryOptions.md @@ -0,0 +1,58 @@ +--- +id: UsePrefetchQueryOptions +title: UsePrefetchQueryOptions +--- + +```ts +type UsePrefetchQueryOptions = DistributiveOmit, "queryFn"> & object; +``` + +Defined in: [react-query/src/types.ts:80](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L80) + +The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, except `queryFn` +is required unless a default query function has been defined. + +## Type Declaration + +### queryFn? + +```ts +optional queryFn: Exclude["queryFn"], SkipToken>; +``` + +`skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, +unless a default query function has been defined. + +## Type Parameters + +### TQueryFnData + +`TQueryFnData` = `unknown` + +The type your `queryFn` resolves to. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. + +### TData + +`TData` = `TQueryFnData` + +The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no +`select` is used. + +### TQueryData + +`TQueryData` = `TQueryFnData` + +The type of the data actually held in the query cache — the input to `select` and +`placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + +### TQueryKey + +`TQueryKey` *extends* `QueryKey` = `QueryKey` + +The type of your `queryKey`. diff --git a/docs/framework/react/reference/type-aliases/UseQueryResult.md b/docs/framework/react/reference/type-aliases/UseQueryResult.md new file mode 100644 index 00000000000..b64fffaf328 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseQueryResult.md @@ -0,0 +1,26 @@ +--- +id: UseQueryResult +title: UseQueryResult +--- + +```ts +type UseQueryResult = UseBaseQueryResult; +``` + +Defined in: [react-query/src/types.ts:325](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L325) + +The result of `useQuery`. Same as [UseBaseQueryResult](UseBaseQueryResult.md). + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/UseSuspenseInfiniteQueryResult.md b/docs/framework/react/reference/type-aliases/UseSuspenseInfiniteQueryResult.md new file mode 100644 index 00000000000..d44b2182610 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseSuspenseInfiniteQueryResult.md @@ -0,0 +1,27 @@ +--- +id: UseSuspenseInfiniteQueryResult +title: UseSuspenseInfiniteQueryResult +--- + +```ts +type UseSuspenseInfiniteQueryResult = OmitKeyof, "isPlaceholderData">; +``` + +Defined in: [react-query/src/types.ts:389](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L389) + +The result of `useSuspenseInfiniteQuery`. Same as [DefinedUseInfiniteQueryResult](DefinedUseInfiniteQueryResult.md), minus +`isPlaceholderData` — Suspense hooks never render placeholder data. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/type-aliases/UseSuspenseQueryResult.md b/docs/framework/react/reference/type-aliases/UseSuspenseQueryResult.md new file mode 100644 index 00000000000..fde2040cab7 --- /dev/null +++ b/docs/framework/react/reference/type-aliases/UseSuspenseQueryResult.md @@ -0,0 +1,27 @@ +--- +id: UseSuspenseQueryResult +title: UseSuspenseQueryResult +--- + +```ts +type UseSuspenseQueryResult = DistributiveOmit, "isPlaceholderData">; +``` + +Defined in: [react-query/src/types.ts:337](https://github.com/TanStack/query/blob/main/packages/react-query/src/types.ts#L337) + +The result of `useSuspenseQuery`. Same as [DefinedUseQueryResult](DefinedUseQueryResult.md), minus `isPlaceholderData` — always +`false` on that type, so this drops the dead field rather than an active state. + +## Type Parameters + +### TData + +`TData` = `unknown` + +The type `data` ends up as after `select` runs. + +### TError + +`TError` = `DefaultError` + +The type of errors your `queryFn` may throw. diff --git a/docs/framework/react/reference/useInfiniteQuery.md b/docs/framework/react/reference/useInfiniteQuery.md deleted file mode 100644 index 0a81d0a4be4..00000000000 --- a/docs/framework/react/reference/useInfiniteQuery.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: useInfiniteQuery -title: useInfiniteQuery ---- - -```tsx -const { - fetchNextPage, - fetchPreviousPage, - hasNextPage, - hasPreviousPage, - isFetchingNextPage, - isFetchingPreviousPage, - ...result -} = useInfiniteQuery({ - queryKey, - queryFn: ({ pageParam }) => fetchPage(pageParam), - initialPageParam: 1, - ...options, - getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => - lastPage.nextCursor, - getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => - firstPage.prevCursor, -}) -``` - -**Options** - -The options for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md) with the addition of the following: - -- `queryFn: (context: QueryFunctionContext) => Promise` - - **Required, but only if no default query function has been defined** [`defaultQueryFn`](../guides/default-query-function.md) - - The function that the query will use to request data. - - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext) - - Must return a promise that will either resolve data or throw an error. -- `initialPageParam: TPageParam` - - **Required** - - The default page param to use when fetching the first page. -- `getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null` - - **Required** - - When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. - - It should return a **single variable** that will be passed as the last optional parameter to your query function. - - Return `undefined` or `null` to indicate there is no next page available. -- `getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined | null` - - When new data is received for this query, this function receives both the first page of the infinite list of data and the full array of all pages, as well as pageParam information. - - It should return a **single variable** that will be passed as the last optional parameter to your query function. - - Return `undefined` or `null`to indicate there is no previous page available. -- `maxPages: number | undefined` - - The maximum number of pages to store in the infinite query data. - - When the maximum number of pages is reached, fetching a new page will result in the removal of either the first or last page from the pages array, depending on the specified direction. - - If `undefined` or equals `0`, the number of pages is unlimited - - Default value is `undefined` - - `getNextPageParam` and `getPreviousPageParam` must be properly defined if `maxPages` value is greater than `0` to allow fetching a page in both directions when needed. - -**Returns** - -The returned properties for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md), with the addition of the following properties and a small difference in `isRefetching` and `isRefetchError`: - -- `data.pages: TData[]` - - Array containing all pages. -- `data.pageParams: unknown[]` - - Array containing all page params. -- `isFetchingNextPage: boolean` - - Will be `true` while fetching the next page with `fetchNextPage`. -- `isFetchingPreviousPage: boolean` - - Will be `true` while fetching the previous page with `fetchPreviousPage`. -- `fetchNextPage: (options?: FetchNextPageOptions) => Promise` - - This function allows you to fetch the next "page" of results. - - `options.cancelRefetch: boolean` if set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, whether the previous - invocation has resolved or not. Also, the result from previous invocations will be ignored. If set to `false`, calling `fetchNextPage` - repeatedly won't have any effect until the first invocation has resolved. Default is `true`. -- `fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise` - - This function allows you to fetch the previous "page" of results. - - `options.cancelRefetch: boolean` same as for `fetchNextPage`. -- `hasNextPage: boolean` - - Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). -- `hasPreviousPage: boolean` - - Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). -- `isFetchNextPageError: boolean` - - Will be `true` if the query failed while fetching the next page. -- `isFetchPreviousPageError: boolean` - - Will be `true` if the query failed while fetching the previous page. -- `isRefetching: boolean` - - Will be `true` whenever a background refetch is in-flight, which _does not_ include initial `pending` or fetching of next or previous page - - Is the same as `isFetching && !isPending && !isFetchingNextPage && !isFetchingPreviousPage` -- `isRefetchError: boolean` - - Will be `true` if the query failed while refetching a page. -Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behaviour, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like `hasNextPage && !isFetching`. diff --git a/docs/framework/react/reference/useIsFetching.md b/docs/framework/react/reference/useIsFetching.md deleted file mode 100644 index a9f027fa54c..00000000000 --- a/docs/framework/react/reference/useIsFetching.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -id: useIsFetching -title: useIsFetching ---- - -`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators). - -```tsx -import { useIsFetching } from '@tanstack/react-query' -// How many queries are fetching? -const isFetching = useIsFetching() -// How many queries matching the posts prefix are fetching? -const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) -``` - -**Options** - -- `filters?: QueryFilters`: [Query Filters](../guides/filters.md#query-filters) -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -**Returns** - -- `isFetching: number` - - Will be the `number` of the queries that your application is currently loading or fetching in the background. diff --git a/docs/framework/react/reference/useIsMutating.md b/docs/framework/react/reference/useIsMutating.md deleted file mode 100644 index b43991c76c6..00000000000 --- a/docs/framework/react/reference/useIsMutating.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -id: useIsMutating -title: useIsMutating ---- - -`useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching (useful for app-wide loading indicators). - -```tsx -import { useIsMutating } from '@tanstack/react-query' -// How many mutations are fetching? -const isMutating = useIsMutating() -// How many mutations matching the posts prefix are fetching? -const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) -``` - -**Options** - -- `filters?: MutationFilters`: [Mutation Filters](../guides/filters.md#mutation-filters) -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -**Returns** - -- `isMutating: number` - - Will be the `number` of the mutations that your application is currently fetching. diff --git a/docs/framework/react/reference/useMutation.md b/docs/framework/react/reference/useMutation.md deleted file mode 100644 index 60940ba5dec..00000000000 --- a/docs/framework/react/reference/useMutation.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -id: useMutation -title: useMutation ---- - -```tsx -const { - data, - error, - isError, - isIdle, - isPending, - isPaused, - isSuccess, - failureCount, - failureReason, - mutate, - mutateAsync, - reset, - status, - submittedAt, - variables, -} = useMutation( - { - mutationFn, - gcTime, - meta, - mutationKey, - networkMode, - onError, - onMutate, - onSettled, - onSuccess, - retry, - retryDelay, - scope, - throwOnError, - }, - queryClient, -) - -mutate(variables, { - onError, - onSettled, - onSuccess, -}) -``` - -**Parameter1 (Options)** - -- `mutationFn: (variables: TVariables, context: MutationFunctionContext) => Promise` - - **Required, but only if no default mutation function has been defined** - - A function that performs an asynchronous task and returns a promise. - - `variables` is an object that `mutate` will pass to your `mutationFn` - - `context` is an object that `mutate` will pass to your `mutationFn`. Contains reference to `QueryClient`, `mutationKey` and optional `meta` object. -- `gcTime: number | Infinity` - - The time in milliseconds that unused/inactive cache data remains in memory. When a mutation's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used. - - If set to `Infinity`, will disable garbage collection - - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider). -- `mutationKey: unknown[]` - - Optional - - A mutation key can be set to inherit defaults set with `queryClient.setMutationDefaults`. -- `networkMode: 'online' | 'always' | 'offlineFirst'` - - Optional - - defaults to `'online'` - - see [Network Mode](../guides/network-mode.md) for more information. -- `onMutate: (variables: TVariables, context: MutationFunctionContext) => Promise | TOnMutateResult | void` - - Optional - - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive - - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds - - The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates. -- `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` - - Optional - - This function will fire when the mutation is successful and will be passed the mutation's result. - - If a promise is returned, it will be awaited and resolved before proceeding -- `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` - - Optional - - This function will fire if the mutation encounters an error and will be passed the error. - - If a promise is returned, it will be awaited and resolved before proceeding -- `onSettled: (data: TData, error: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` - - Optional - - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error - - If a promise is returned, it will be awaited and resolved before proceeding -- `retry: boolean | number | (failureCount: number, error: TError) => boolean` - - Defaults to `0`. - - If `false`, failed mutations will not retry. - - If `true`, failed mutations will retry infinitely. - - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. -- `retryDelay: number | (retryAttempt: number, error: TError) => number` - - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. - - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. - - A function like `attempt => attempt * 1000` applies linear backoff. -- `scope: { id: string }` - - Optional - - Defaults to a unique id (so that all mutations run in parallel) - - Mutations with the same scope id will run in serial -- `throwOnError: undefined | boolean | (error: TError) => boolean` - - Set this to `true` if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary - - Set this to `false` to disable the behavior of throwing errors to the error boundary. - - If set to a function, it will be passed the error and should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`) -- `meta: Record` - - Optional - - If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`). - -**Parameter2 (QueryClient)** - -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -**Returns** - -- `mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void` - - The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. - - `variables: TVariables` - - Optional - - The variables object to pass to the `mutationFn`. - - `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` - - Optional - - This function will fire when the mutation is successful and will be passed the mutation's result. - - Void function, the returned value will be ignored - - `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` - - Optional - - This function will fire if the mutation encounters an error and will be passed the error. - - Void function, the returned value will be ignored - - `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` - - Optional - - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error - - Void function, the returned value will be ignored - - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. -- `mutateAsync: (variables: TVariables, { onSuccess, onSettled, onError }) => Promise` - - Similar to `mutate` but returns a promise which can be awaited. -- `status: MutationStatus` - - Will be: - - `idle` initial status prior to the mutation function executing. - - `pending` if the mutation is currently executing. - - `error` if the last mutation attempt resulted in an error. - - `success` if the last mutation attempt was successful. -- `isIdle`, `isPending`, `isSuccess`, `isError`: boolean variables derived from `status` -- `isPaused: boolean` - - will be `true` if the mutation has been `paused` - - see [Network Mode](../guides/network-mode.md) for more information. -- `data: undefined | unknown` - - Defaults to `undefined` - - The last successfully resolved data for the mutation. -- `error: null | TError` - - The error object for the query, if an error was encountered. -- `reset: () => void` - - A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). -- `failureCount: number` - - The failure count for the mutation. - - Incremented every time the mutation fails. - - Reset to `0` when the mutation succeeds. -- `failureReason: null | TError` - - The failure reason for the mutation retry. - - Reset to `null` when the mutation succeeds. -- `submittedAt: number` - - The timestamp for when the mutation was submitted. - - Defaults to `0`. -- `variables: undefined | TVariables` - - The `variables` object passed to the `mutationFn`. - - Defaults to `undefined`. diff --git a/docs/framework/react/reference/useMutationState.md b/docs/framework/react/reference/useMutationState.md deleted file mode 100644 index 60ee59e92fd..00000000000 --- a/docs/framework/react/reference/useMutationState.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -id: useMutationState -title: useMutationState ---- - -`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state. - -**Example 1: Get all variables of all running mutations** - -```tsx -import { useMutationState } from '@tanstack/react-query' - -const variables = useMutationState({ - filters: { status: 'pending' }, - select: (mutation) => mutation.state.variables, -}) -``` - -**Example 2: Get all data for specific mutations via the `mutationKey`** - -```tsx -import { useMutation, useMutationState } from '@tanstack/react-query' - -const mutationKey = ['posts'] - -// Some mutation that we want to get the state for -const mutation = useMutation({ - mutationKey, - mutationFn: (newPost) => { - return axios.post('/posts', newPost) - }, -}) - -const data = useMutationState({ - // this mutation key needs to match the mutation key of the given mutation (see above) - filters: { mutationKey }, - select: (mutation) => mutation.state.data, -}) -``` - -**Example 3: Access the latest mutation data via the `mutationKey`**. -Each invocation of `mutate` adds a new entry to the mutation cache for `gcTime` milliseconds. - -To access the latest invocation, you can check for the last item that `useMutationState` returns. - -```tsx -import { useMutation, useMutationState } from '@tanstack/react-query' - -const mutationKey = ['posts'] - -// Some mutation that we want to get the state for -const mutation = useMutation({ - mutationKey, - mutationFn: (newPost) => { - return axios.post('/posts', newPost) - }, -}) - -const data = useMutationState({ - // this mutation key needs to match the mutation key of the given mutation (see above) - filters: { mutationKey }, - select: (mutation) => mutation.state.data, -}) - -// Latest mutation data -const latest = data[data.length - 1] -``` - -**Options** - -- `options` - - `filters?: MutationFilters`: [Mutation Filters](../guides/filters.md#mutation-filters) - - `select?: (mutation: Mutation) => TResult` - - Use this to transform the mutation state. -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -**Returns** - -- `Array` - - Will be an Array of whatever `select` returns for each matching mutation. diff --git a/docs/framework/react/reference/usePrefetchInfiniteQuery.md b/docs/framework/react/reference/usePrefetchInfiniteQuery.md deleted file mode 100644 index 497eb950d46..00000000000 --- a/docs/framework/react/reference/usePrefetchInfiniteQuery.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -id: usePrefetchInfiniteQuery -title: usePrefetchInfiniteQuery ---- - -```tsx -usePrefetchInfiniteQuery(options) -``` - -**Options** - -You can pass everything to `usePrefetchInfiniteQuery` that you can pass to [`queryClient.infiniteQuery`](../../../reference/QueryClient.md#queryclient-infinitequery). Remember that some of them are required as below: - -- `queryKey: QueryKey` - - **Required** - - The query key to prefetch during render - -- `queryFn: (context: QueryFunctionContext) => Promise` - - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. - -- `initialPageParam: TPageParam` - - **Required** - - The default page param to use when fetching the first page. - -- `getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null` - - **Required** - - When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. - - It should return a **single variable** that will be passed as the last optional parameter to your query function. - - Return `undefined` or `null` to indicate there is no next page available. - -- **Returns** - -The `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, before a suspense boundary that wraps a component that uses [`useSuspenseInfiniteQuery`](./useSuspenseInfiniteQuery.md) diff --git a/docs/framework/react/reference/usePrefetchQuery.md b/docs/framework/react/reference/usePrefetchQuery.md deleted file mode 100644 index 593afd350f8..00000000000 --- a/docs/framework/react/reference/usePrefetchQuery.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -id: usePrefetchQuery -title: usePrefetchQuery ---- - -```tsx -usePrefetchQuery(options) -``` - -**Options** - -You can pass everything to `usePrefetchQuery` that you can pass to [`queryClient.query`](../../../reference/QueryClient.md#queryclient-query). Remember that some of them are required as below: - -- `queryKey: QueryKey` - - **Required** - - The query key to prefetch during render - -- `queryFn: (context: QueryFunctionContext) => TQueryFnData | Promise` - - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. - -**Returns** - -The `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before a suspense boundary that wraps a component that uses [`useSuspenseQuery`](./useSuspenseQuery.md). diff --git a/docs/framework/react/reference/useQueries.md b/docs/framework/react/reference/useQueries.md deleted file mode 100644 index 1048b532d29..00000000000 --- a/docs/framework/react/reference/useQueries.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -id: useQueries -title: useQueries ---- - -The `useQueries` hook can be used to fetch a variable number of queries: - -```tsx -const ids = [1, 2, 3] -const results = useQueries({ - queries: ids.map((id) => ({ - queryKey: ['post', id], - queryFn: () => fetchPost(id), - staleTime: Infinity, - })), -}) -``` - -**Options** - -The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](./useQuery.md) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level). - -- `queryClient?: QueryClient` - - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used. -- `combine?: (result: UseQueriesResults) => TCombinedResult` - - Use this to combine the results of the queries into a single value. - -> Having the same query key more than once in the array of query objects may cause some data to be shared between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired structure. - -**placeholderData** - -The `placeholderData` option exists for `useQueries` as well, but it doesn't get information passed from previously rendered Queries like `useQuery` does, because the input to `useQueries` can be a different number of Queries on each render. - -**Returns** - -The `useQueries` hook returns an array with all the query results. The order returned is the same as the input order. - -## Combine - -If you want to combine `data` (or other Query information) from the results into a single value, you can use the `combine` option. The result will be structurally shared to be as referentially stable as possible. - -```tsx -const ids = [1, 2, 3] -const combinedQueries = useQueries({ - queries: ids.map((id) => ({ - queryKey: ['post', id], - queryFn: () => fetchPost(id), - })), - combine: (results) => { - return { - data: results.map((result) => result.data), - pending: results.some((result) => result.isPending), - } - }, -}) -``` - -In the above example, `combinedQueries` will be an object with a `data` and a `pending` property. Note that all other properties of the Query results will be lost. - -### Memoization - -The `combine` function will only re-run if: - -- the `combine` function itself changed referentially -- any of the query results changed - -This means that an inlined `combine` function, as shown above, will run on every render. To avoid this, you can wrap the `combine` function in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies. - -## TypeScript: typing the `select` option - -Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls back to `unknown`. This is a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). - -```tsx -useQueries({ - queries: [ - { - queryKey: ['post', 1], - queryFn: () => fetchPost(1), - // ❌ `data` is `unknown` here - select: (data) => data.title, - }, - ], -}) -``` - -There are two supported workarounds: - -1. Annotate the `select` parameter explicitly: - -```tsx -useQueries({ - queries: [ - { - queryKey: ['post', 1], - queryFn: () => fetchPost(1), - // ✅ `data` is `Post` - select: (data: Post) => data.title, - }, - ], -}) -``` - -2. Define the query with the [`queryOptions`](./queryOptions.md) helper, which resolves its types in a single object _before_ it reaches `useQueries`: - -```tsx -const postOptions = (id: number) => - queryOptions({ - queryKey: ['post', id], - queryFn: () => fetchPost(id), - // ✅ `data` is `Post` - select: (data) => data.title, - }) - -useQueries({ queries: [postOptions(1), postOptions(2)] }) -``` - -The same limitation applies when you spread a `queryOptions` result to override its `select` inline — the overriding `select` still falls back to `unknown`: - -```tsx -useQueries({ - queries: [ - { - ...postOptions(1), - // ❌ `data` is `unknown` here - select: (data) => data.title, - }, - ], -}) -``` - -Wrap the spread in `queryOptions` again so the override is resolved before it reaches `useQueries`: - -```tsx -useQueries({ - queries: [ - queryOptions({ - ...postOptions(1), - // ✅ `data` is `Post` - select: (data) => data.title, - }), - ], -}) -``` - -The same applies to [`useSuspenseQueries`](./useSuspenseQueries.md). diff --git a/docs/framework/react/reference/useQuery.md b/docs/framework/react/reference/useQuery.md deleted file mode 100644 index 10f6df3aeeb..00000000000 --- a/docs/framework/react/reference/useQuery.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -id: useQuery -title: useQuery ---- - -```tsx -const { - data, - dataUpdatedAt, - error, - errorUpdateCount, - errorUpdatedAt, - failureCount, - failureReason, - fetchStatus, - isError, - isFetched, - isFetchedAfterMount, - isFetching, - isInitialLoading, - isLoading, - isLoadingError, - isPaused, - isPending, - isPlaceholderData, - isRefetchError, - isRefetching, - isStale, - isSuccess, - isEnabled, - refetch, - status, -} = useQuery( - { - queryKey, - queryFn, - gcTime, - enabled, - networkMode, - initialData, - initialDataUpdatedAt, - meta, - notifyOnChangeProps, - placeholderData, - queryKeyHashFn, - refetchInterval, - refetchIntervalInBackground, - refetchOnMount, - refetchOnReconnect, - refetchOnWindowFocus, - retry, - retryOnMount, - retryDelay, - select, - staleTime, - structuralSharing, - subscribed, - throwOnError, - }, - queryClient, -) -``` - -**Parameter1 (Options)** - -- `queryKey: unknown[]` - - **Required** - - The query key to use for this query. - - The query key will be hashed into a stable hash. See [Query Keys](../guides/query-keys.md) for more information. - - The query will automatically update when this key changes (as long as `enabled` is not set to `false`). -- `queryFn: (context: QueryFunctionContext) => Promise` - - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. - - The function that the query will use to request data. - - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext) - - Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. -- `enabled: boolean | (query: Query) => boolean` - - Set this to `false` to disable this query from automatically running. - - Can be used for [Dependent Queries](../guides/dependent-queries.md). -- `networkMode: 'online' | 'always' | 'offlineFirst'` - - optional - - defaults to `'online'` - - see [Network Mode](../guides/network-mode.md) for more information. -- `retry: boolean | number | (failureCount: number, error: TError) => boolean` - - If `false`, failed queries will not retry by default. - - If `true`, failed queries will retry infinitely. - - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. - - If set to a function, it will be called with `failureCount` (starting at `0` for the first retry) and `error` to determine if a retry should be attempted. - - defaults to `3` on the client and `0` on the server -- `retryOnMount: boolean | (query: Query) => boolean` - - If set to `false`, the query will not be retried on mount if it contains an error and has no data. Defaults to `true`. - - If set to a function, the function will be executed with the query to compute the value. -- `retryDelay: number | (retryAttempt: number, error: TError) => number` - - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. - - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. - - A function like `attempt => attempt * 1000` applies linear backoff. -- `staleTime: number | 'static' | ((query: Query) => number | 'static')` - - Optional - - Defaults to `0` - - The time in milliseconds after which data is considered stale. This value only applies to the hook it is defined on. - - If set to `Infinity`, the data will not be considered stale unless manually invalidated - - If set to a function, the function will be executed with the query to compute a `staleTime`. - - If set to `'static'`, the data will never be considered stale -- `gcTime: number | Infinity` - - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR - - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. - - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider). - - If set to `Infinity`, will disable garbage collection -- `queryKeyHashFn: (queryKey: QueryKey) => string` - - Optional - - If specified, this function is used to hash the `queryKey` to a string. -- `refetchInterval: number | false | ((query: Query) => number | false | undefined)` - - Optional - - If set to a number, all queries will continuously refetch at this frequency in milliseconds - - If set to a function, the function will be executed with the query to compute a frequency -- `refetchIntervalInBackground: boolean` - - Optional - - If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background -- `refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")` - - Optional - - Defaults to `true` - - If set to `true`, the query will refetch on mount if the data is stale. - - If set to `false`, the query will not refetch on mount. - - If set to `"always"`, the query will always refetch on mount (except when `staleTime: 'static'` is used). - - If set to a function, the function will be executed with the query to compute the value -- `refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")` - - Optional - - Defaults to `true` - - If set to `true`, the query will refetch on window focus if the data is stale. - - If set to `false`, the query will not refetch on window focus. - - If set to `"always"`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). - - If set to a function, the function will be executed with the query to compute the value -- `refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")` - - Optional - - Defaults to `true` - - If set to `true`, the query will refetch on reconnect if the data is stale. - - If set to `false`, the query will not refetch on reconnect. - - If set to `"always"`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). - - If set to a function, the function will be executed with the query to compute the value -- `notifyOnChangeProps: string[] | "all" | (() => string[] | "all" | undefined)` - - Optional - - If set, the component will only re-render if any of the listed properties change. - - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. - - If set to `"all"`, the component will opt-out of smart tracking and re-render whenever a query is updated. - - If set to a function, the function will be executed to compute the list of properties. - - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. -- `select: (data: TData) => unknown` - - Optional - - This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. - - The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. To optimize, wrap the function in `useCallback`. -- `initialData: TData | () => TData` - - Optional - - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) - - If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData - - Initial data is considered stale by default unless a `staleTime` has been set. - - `initialData` **is persisted** to the cache -- `initialDataUpdatedAt: number | (() => number | undefined)` - - Optional - - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. -- `placeholderData: TData | (previousValue: TData | undefined, previousQuery: Query | undefined) => TData` - - Optional - - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. - - `placeholderData` is **not persisted** to the cache - - If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. -- `structuralSharing: boolean | (oldData: unknown | undefined, newData: unknown) => unknown` - - Optional - - Defaults to `true` - - If set to `false`, structural sharing between query results will be disabled. - - If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. -- `subscribed: boolean` - - Optional - - Defaults to `true` - - If set to `false`, this instance of `useQuery` will not be subscribed to the cache. This means it won't trigger the `queryFn` on its own, and it won't receive updates if data gets into cache by other means. -- `throwOnError: undefined | boolean | (error: TError, query: Query) => boolean` - - Optional - - Defaults to `false` - - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary - - If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`) -- `meta: Record` - - Optional - - If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. - -**Parameter2 (QueryClient)** - -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. - -**Returns** - -- `status: QueryStatus` - - Will be: - - `pending` if there's no cached data and no query attempt was finished yet. - - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch - - `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization. -- `isPending: boolean` - - A derived boolean from the `status` variable above, provided for convenience. -- `isSuccess: boolean` - - A derived boolean from the `status` variable above, provided for convenience. -- `isError: boolean` - - A derived boolean from the `status` variable above, provided for convenience. -- `isLoadingError: boolean` - - Will be `true` if the query failed while fetching for the first time. -- `isRefetchError: boolean` - - Will be `true` if the query failed while refetching. -- `data: TData` - - Defaults to `undefined`. - - The last successfully resolved data for the query. -- `dataUpdatedAt: number` - - The timestamp for when the query most recently returned the `status` as `"success"`. -- `error: null | TError` - - Defaults to `null` - - The error object for the query, if an error was thrown. -- `errorUpdatedAt: number` - - The timestamp for when the query most recently returned the `status` as `"error"`. -- `isStale: boolean` - - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. -- `isPlaceholderData: boolean` - - Will be `true` if the data shown is the placeholder data. -- `isFetched: boolean` - - Will be `true` if the query has been fetched. -- `isFetchedAfterMount: boolean` - - Will be `true` if the query has been fetched after the component mounted. - - This property can be used to not show any previously cached data. -- `fetchStatus: FetchStatus` - - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches. - - `paused`: The query wanted to fetch, but has been `paused`. - - `idle`: The query is not fetching. - - see [Network Mode](../guides/network-mode.md) for more information. -- `isFetching: boolean` - - A derived boolean from the `fetchStatus` variable above, provided for convenience. -- `isPaused: boolean` - - A derived boolean from the `fetchStatus` variable above, provided for convenience. -- `isRefetching: boolean` - - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending` - - Is the same as `isFetching && !isPending` -- `isLoading: boolean` - - Is `true` whenever the first fetch for a query is in-flight - - Is the same as `isFetching && isPending` -- `isInitialLoading: boolean` - - **deprecated** - - An alias for `isLoading`, will be removed in the next major version. -- `isEnabled: boolean` - - Is `true` if this query observer is enabled, `false` otherwise. -- `failureCount: number` - - The failure count for the query. - - Incremented every time the query fails. - - Reset to `0` when the query succeeds. -- `failureReason: null | TError` - - The failure reason for the query retry. - - Reset to `null` when the query succeeds. -- `errorUpdateCount: number` - - The sum of all errors. -- `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise` - - A function to manually refetch the query. - - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option - - `cancelRefetch?: boolean` - - Defaults to `true` - - Per default, a currently running request will be cancelled before a new request is made - - When set to `false`, no refetch will be made if there is already a request running. diff --git a/docs/framework/react/reference/useQueryClient.md b/docs/framework/react/reference/useQueryClient.md deleted file mode 100644 index 4fb04c1bf76..00000000000 --- a/docs/framework/react/reference/useQueryClient.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -id: useQueryClient -title: useQueryClient ---- - -The `useQueryClient` hook returns the current `QueryClient` instance. - -```tsx -import { useQueryClient } from '@tanstack/react-query' - -const queryClient = useQueryClient(queryClient?: QueryClient) -``` - -**Options** - -- `queryClient?: QueryClient` - - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. diff --git a/docs/framework/react/reference/useQueryErrorResetBoundary.md b/docs/framework/react/reference/useQueryErrorResetBoundary.md deleted file mode 100644 index 9c970678be4..00000000000 --- a/docs/framework/react/reference/useQueryErrorResetBoundary.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -id: useQueryErrorResetBoundary -title: useQueryErrorResetBoundary ---- - -This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary defined it will reset them globally: - -```tsx -import { useQueryErrorResetBoundary } from '@tanstack/react-query' -import { ErrorBoundary } from 'react-error-boundary' - -const App = () => { - const { reset } = useQueryErrorResetBoundary() - return ( - ( -
- There was an error! - -
- )} - > - -
- ) -} -``` diff --git a/docs/framework/react/reference/useSuspenseInfiniteQuery.md b/docs/framework/react/reference/useSuspenseInfiniteQuery.md deleted file mode 100644 index 6cedddaaed8..00000000000 --- a/docs/framework/react/reference/useSuspenseInfiniteQuery.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -id: useSuspenseInfiniteQuery -title: useSuspenseInfiniteQuery ---- - -```tsx -const result = useSuspenseInfiniteQuery(options) -``` - -**Options** - -The same as for [useInfiniteQuery](./useInfiniteQuery.md), except for: - -- `throwOnError` -- `enabled` -- `placeholderData` - -**Returns** - -Same object as [useInfiniteQuery](./useInfiniteQuery.md), except that: - -- `data` is guaranteed to be defined -- `isPlaceholderData` is missing -- `status` is either `success` or `error` - - the derived flags are set accordingly. - -**Caveat** - -[Cancellation](../guides/query-cancellation.md) does not work. diff --git a/docs/framework/react/reference/useSuspenseQueries.md b/docs/framework/react/reference/useSuspenseQueries.md deleted file mode 100644 index 0b10231f0cd..00000000000 --- a/docs/framework/react/reference/useSuspenseQueries.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -id: useSuspenseQueries -title: useSuspenseQueries ---- - -```tsx -const result = useSuspenseQueries(options) -``` - -**Options** - -The same as for [useQueries](./useQueries.md), except that each `query` can't have: - -- `throwOnError` -- `enabled` -- `placeholderData` - -> The [`select` typing caveat](./useQueries.md#typescript-typing-the-select-option) for `useQueries` applies here as well: annotate the `select` parameter or use the [`queryOptions`](./queryOptions.md) helper to keep type inference. - -**Returns** - -Same structure as [useQueries](./useQueries.md), except that for each `query`: - -- `data` is guaranteed to be defined -- `isPlaceholderData` is missing -- `status` is either `success` or `error` - - the derived flags are set accordingly. - -**Caveats** - -Keep in mind that the component will only re-mount after **all queries** have finished loading. Hence, if a query has gone stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid this, make sure to set a high enough `staleTime`. - -[Cancellation](../guides/query-cancellation.md) does not work. diff --git a/docs/framework/react/reference/useSuspenseQuery.md b/docs/framework/react/reference/useSuspenseQuery.md deleted file mode 100644 index b531bca47d2..00000000000 --- a/docs/framework/react/reference/useSuspenseQuery.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -id: useSuspenseQuery -title: useSuspenseQuery ---- - -```tsx -const result = useSuspenseQuery(options) -``` - -**Options** - -The same as for [useQuery](./useQuery.md), except for: - -- `throwOnError` -- `enabled` -- `placeholderData` - -**Returns** - -Same object as [useQuery](./useQuery.md), except that: - -- `data` is guaranteed to be defined -- `isPlaceholderData` is missing -- `status` is either `success` or `error` - - the derived flags are set accordingly. - -**Caveat** - -[Cancellation](../guides/query-cancellation.md) does not work. diff --git a/docs/framework/react/reference/variables/IsRestoringProvider.md b/docs/framework/react/reference/variables/IsRestoringProvider.md new file mode 100644 index 00000000000..e320fdaefe0 --- /dev/null +++ b/docs/framework/react/reference/variables/IsRestoringProvider.md @@ -0,0 +1,13 @@ +--- +id: IsRestoringProvider +title: IsRestoringProvider +--- + +```ts +const IsRestoringProvider: Provider = IsRestoringContext.Provider; +``` + +Defined in: [react-query/src/IsRestoringProvider.ts:19](https://github.com/TanStack/query/blob/main/packages/react-query/src/IsRestoringProvider.ts#L19) + +The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently +being restored, read by `useIsRestoring`. diff --git a/docs/framework/react/reference/variables/QueryClientContext.md b/docs/framework/react/reference/variables/QueryClientContext.md new file mode 100644 index 00000000000..20619cd18df --- /dev/null +++ b/docs/framework/react/reference/variables/QueryClientContext.md @@ -0,0 +1,12 @@ +--- +id: QueryClientContext +title: QueryClientContext +--- + +```ts +const QueryClientContext: Context; +``` + +Defined in: [react-query/src/QueryClientProvider.tsx:9](https://github.com/TanStack/query/blob/main/packages/react-query/src/QueryClientProvider.tsx#L9) + +The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/docs/framework/react/typescript.md b/docs/framework/react/typescript.md index 28c242df41c..6349a076de1 100644 --- a/docs/framework/react/typescript.md +++ b/docs/framework/react/typescript.md @@ -155,7 +155,7 @@ const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups }) ### Registering global Meta -Similarly to registering a [global error type](#registering-a-global-error) you can also register a global `Meta` type. This ensures the optional `meta` field on [queries](./reference/useQuery.md) and [mutations](./reference/useMutation.md) stays consistent and is type-safe. Note that the registered type must extend `Record` so that `meta` remains an object. +Similarly to registering a [global error type](#registering-a-global-error) you can also register a global `Meta` type. This ensures the optional `meta` field on [queries](./reference/functions/useQuery.md) and [mutations](./reference/functions/useMutation.md) stays consistent and is type-safe. Note that the registered type must extend `Record` so that `meta` remains an object. ```ts import '@tanstack/react-query' diff --git a/docs/framework/solid/reference/hydration.md b/docs/framework/solid/reference/hydration.md index 77b37b1c8ca..f2007dea7ec 100644 --- a/docs/framework/solid/reference/hydration.md +++ b/docs/framework/solid/reference/hydration.md @@ -1,9 +1,98 @@ --- id: hydration title: hydration -ref: docs/framework/react/reference/hydration.md -replace: { '@tanstack/react-query': '@tanstack/solid-query' } --- -[//]: # 'HydrationBoundary' -[//]: # 'HydrationBoundary' +## `dehydrate` + +`dehydrate` creates a frozen representation of a `cache` that can later be hydrated with `hydrate`. This is useful for passing prefetched queries from server to client or persisting queries to localStorage or other persistent locations. It only includes currently successful queries by default. + +```ts +import { dehydrate } from '@tanstack/solid-query' + +const dehydratedState = dehydrate(queryClient, { + shouldDehydrateQuery, + shouldDehydrateMutation, +}) +``` + +**Options** + +- `client: QueryClient` + - **Required** + - The `queryClient` that should be dehydrated +- `options: DehydrateOptions` + - Optional + - `shouldDehydrateMutation: (mutation: Mutation) => boolean` + - Optional + - Whether to dehydrate mutations. + - The function is called for each mutation in the cache + - Return `true` to include this mutation in dehydration, or `false` otherwise + - Defaults to only including paused mutations + - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateMutation` as part of the return statement + - `shouldDehydrateQuery: (query: Query) => boolean` + - Optional + - Whether to dehydrate queries. + - The function is called for each query in the cache + - Return `true` to include this query in dehydration, or `false` otherwise + - Defaults to only including successful queries + - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateQuery` as part of the return statement + - `serializeData?: (data: any) => any` A function to transform (serialize) data during dehydration. + - `shouldRedactErrors?: (error: unknown) => boolean` + - Optional + - Only applies to queries that are still `pending` at dehydration time — their promise is dehydrated too, and this function decides whether to redact the error if that promise later rejects. + - The function is called with that rejection error + - Return `true` to redact it, or `false` otherwise + - Defaults to redacting all such errors + - Does **not** apply to `query.state.error` on already-settled queries — that error is included in the dehydrated state as-is, so sanitize it yourself via `shouldDehydrateQuery` if it may contain sensitive data + +**Returns** + +- `dehydratedState: DehydratedState` + - This includes everything that is needed to hydrate the `queryClient` at a later point + - You **should not** rely on the exact format of this response, it is not part of the public API and can change at any time + - This result is not in serialized form, you need to do that yourself if desired + +### Limitations + +Some storage systems (such as browser [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)) require values to be JSON serializable. If you need to dehydrate values that are not automatically serializable to JSON (like `Error` or `undefined`), you have to serialize them for yourself. Since only successful queries are included per default, to also include `Errors`, you have to provide `shouldDehydrateQuery`, e.g.: + +```ts +// server +const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors +const serializedState = mySerialize(state) // transform Error instances to objects + +// client +const state = myDeserialize(serializedState) // transform objects back to Error instances +hydrate(client, state) +``` + +## `hydrate` + +`hydrate` adds a previously dehydrated state into a `cache`. + +```ts +import { hydrate } from '@tanstack/solid-query' + +hydrate(queryClient, dehydratedState, options) +``` + +**Options** + +- `client: QueryClient` + - **Required** + - The `queryClient` to hydrate the state into +- `dehydratedState: DehydratedState` + - **Required** + - The state to hydrate into the client +- `options: HydrateOptions` + - Optional + - `defaultOptions: DefaultOptions` + - Optional + - `mutations: MutationOptions` The default mutation options to use for the hydrated mutations. + - `queries: QueryOptions` The default query options to use for the hydrated queries. + - `deserializeData?: (data: any) => any` A function to transform (deserialize) data before it is put into the cache. + +### Limitations + +If the queries you're trying to hydrate already exist in the queryCache, `hydrate` will only overwrite them if the data is newer than the data present in the cache. Otherwise, it will **not** get applied. diff --git a/docs/framework/solid/reference/infiniteQueryOptions.md b/docs/framework/solid/reference/infiniteQueryOptions.md index fa4b38aae98..5455c2a440f 100644 --- a/docs/framework/solid/reference/infiniteQueryOptions.md +++ b/docs/framework/solid/reference/infiniteQueryOptions.md @@ -1,5 +1,21 @@ --- id: infiniteQueryOptions title: infiniteQueryOptions -ref: docs/framework/react/reference/infiniteQueryOptions.md --- + +```tsx +infiniteQueryOptions({ + queryKey, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to [`useInfiniteQuery`](./useInfiniteQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + +- `queryKey: QueryKey` + - **Required** + - The query key to generate options for. + +See [useInfiniteQuery](./useInfiniteQuery.md) for more information. diff --git a/docs/framework/solid/reference/mutationOptions.md b/docs/framework/solid/reference/mutationOptions.md index b34296ad545..0fa145a890f 100644 --- a/docs/framework/solid/reference/mutationOptions.md +++ b/docs/framework/solid/reference/mutationOptions.md @@ -1,5 +1,15 @@ --- id: mutationOptions title: mutationOptions -ref: docs/framework/react/reference/mutationOptions.md --- + +```tsx +mutationOptions({ + mutationFn, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `mutationOptions` that you can also pass to [`useMutation`](./useMutation.md). diff --git a/docs/framework/solid/reference/queryOptions.md b/docs/framework/solid/reference/queryOptions.md index 401cf8d1043..f6f0ac7f2e9 100644 --- a/docs/framework/solid/reference/queryOptions.md +++ b/docs/framework/solid/reference/queryOptions.md @@ -1,5 +1,26 @@ --- id: queryOptions title: queryOptions -ref: docs/framework/react/reference/queryOptions.md --- + +```tsx +queryOptions({ + queryKey, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `queryOptions` that you can also pass to [`useQuery`](./useQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.query`. + +- `queryKey: QueryKey` + - **Required** + - The query key to generate options for. +[//]: # 'Materials' + +## Further reading + +To learn more about `QueryOptions`, have a look at [this article by TkDodo The Query Options API](https://tkdodo.eu/blog/the-query-options-api). + +[//]: # 'Materials' diff --git a/docs/framework/solid/reference/useInfiniteQuery.md b/docs/framework/solid/reference/useInfiniteQuery.md index 48f0425210d..8ae5861e083 100644 --- a/docs/framework/solid/reference/useInfiniteQuery.md +++ b/docs/framework/solid/reference/useInfiniteQuery.md @@ -1,11 +1,88 @@ --- id: useInfiniteQuery title: useInfiniteQuery -ref: docs/framework/react/reference/useInfiniteQuery.md -replace: - { - '@tanstack/react-query': '@tanstack/solid-query', - 'useInfiniteQuery[(]': 'useInfiniteQuery(() => ', - 'useMutation[(]': 'useMutation(() => ', - } --- + +```tsx +const { + fetchNextPage, + fetchPreviousPage, + hasNextPage, + hasPreviousPage, + isFetchingNextPage, + isFetchingPreviousPage, + ...result +} = useInfiniteQuery(() => ({ + queryKey, + queryFn: ({ pageParam }) => fetchPage(pageParam), + initialPageParam: 1, + ...options, + getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => + lastPage.nextCursor, + getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => + firstPage.prevCursor, +})) +``` + +**Options** + +The options for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md) with the addition of the following: + +- `queryFn: (context: QueryFunctionContext) => Promise` + - **Required, but only if no default query function has been defined** [`defaultQueryFn`](../guides/default-query-function.md) + - The function that the query will use to request data. + - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext) + - Must return a promise that will either resolve data or throw an error. +- `initialPageParam: TPageParam` + - **Required** + - The default page param to use when fetching the first page. +- `getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null` + - **Required** + - When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. + - It should return a **single variable** that will be passed as `pageParam` on your query function's context object (e.g. `queryFn: ({ pageParam }) => ...`). + - Return `undefined` or `null` to indicate there is no next page available. +- `getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined | null` + - When new data is received for this query, this function receives both the first page of the infinite list of data and the full array of all pages, as well as pageParam information. + - It should return a **single variable** that will be passed as `pageParam` on your query function's context object (e.g. `queryFn: ({ pageParam }) => ...`). + - Return `undefined` or `null`to indicate there is no previous page available. +- `maxPages: number | undefined` + - The maximum number of pages to store in the infinite query data. + - When the maximum number of pages is reached, fetching a new page will result in the removal of either the first or last page from the pages array, depending on the specified direction. + - If `undefined` or equals `0`, the number of pages is unlimited + - Default value is `undefined` + - `getNextPageParam` and `getPreviousPageParam` must be properly defined if `maxPages` value is greater than `0` to allow fetching a page in both directions when needed. + +**Returns** + +The returned properties for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md), with the addition of the following properties and a small difference in `isRefetching` and `isRefetchError`: + +- `data.pages: TData[]` + - Array containing all pages. +- `data.pageParams: unknown[]` + - Array containing all page params. +- `isFetchingNextPage: boolean` + - Will be `true` while fetching the next page with `fetchNextPage`. +- `isFetchingPreviousPage: boolean` + - Will be `true` while fetching the previous page with `fetchPreviousPage`. +- `fetchNextPage: (options?: FetchNextPageOptions) => Promise` + - This function allows you to fetch the next "page" of results. + - `options.cancelRefetch: boolean` if set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, whether the previous + invocation has resolved or not. Also, the result from previous invocations will be ignored. If set to `false`, calling `fetchNextPage` + repeatedly won't have any effect until the first invocation has resolved. Default is `true`. +- `fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise` + - This function allows you to fetch the previous "page" of results. + - `options.cancelRefetch: boolean` same as for `fetchNextPage`. +- `hasNextPage: boolean` + - Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). +- `hasPreviousPage: boolean` + - Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). +- `isFetchNextPageError: boolean` + - Will be `true` if the query failed while fetching the next page. +- `isFetchPreviousPageError: boolean` + - Will be `true` if the query failed while fetching the previous page. +- `isRefetching: boolean` + - Will be `true` whenever a background refetch is in-flight, which _does not_ include initial `pending` or fetching of next or previous page + - Is the same as `isFetching && !isPending && !isFetchingNextPage && !isFetchingPreviousPage` +- `isRefetchError: boolean` + - Will be `true` if the query failed while refetching a page. +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behaviour, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like `hasNextPage && !isFetching`. diff --git a/docs/framework/solid/reference/useIsFetching.md b/docs/framework/solid/reference/useIsFetching.md index ba7ffeb35f6..02ce5f18330 100644 --- a/docs/framework/solid/reference/useIsFetching.md +++ b/docs/framework/solid/reference/useIsFetching.md @@ -1,6 +1,27 @@ --- id: useIsFetching title: useIsFetching -ref: docs/framework/react/reference/useIsFetching.md -replace: { '@tanstack/react-query': '@tanstack/solid-query' } --- + +`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators). + +```tsx +import { useIsFetching } from '@tanstack/solid-query' +// How many queries are fetching? +const isFetching = useIsFetching() +isFetching() +// How many queries matching the posts prefix are fetching? +const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] })) +isFetchingPosts() +``` + +**Options** + +- `filters?: Accessor`: [Query Filters](../guides/filters.md#query-filters) +- `queryClient?: Accessor` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `isFetching: Accessor` + - Will resolve to the `number` of the queries that your application is currently loading or fetching in the background. diff --git a/docs/framework/solid/reference/useIsMutating.md b/docs/framework/solid/reference/useIsMutating.md index 42c3e3fa2fd..5711d84d53e 100644 --- a/docs/framework/solid/reference/useIsMutating.md +++ b/docs/framework/solid/reference/useIsMutating.md @@ -1,6 +1,27 @@ --- id: useIsMutating title: useIsMutating -ref: docs/framework/react/reference/useIsMutating.md -replace: { '@tanstack/react-query': '@tanstack/solid-query' } --- + +`useIsMutating` is an optional hook that returns the `number` of mutations that your application is currently in a `pending` state with (useful for app-wide loading indicators). + +```tsx +import { useIsMutating } from '@tanstack/solid-query' +// How many mutations are pending? +const isMutating = useIsMutating() +isMutating() +// How many mutations matching the posts prefix are pending? +const isMutatingPosts = useIsMutating(() => ({ mutationKey: ['posts'] })) +isMutatingPosts() +``` + +**Options** + +- `filters?: Accessor`: [Mutation Filters](../guides/filters.md#mutation-filters) +- `queryClient?: Accessor` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `isMutating: Accessor` + - Will resolve to the `number` of the mutations that your application is currently pending with. diff --git a/docs/framework/solid/reference/useMutation.md b/docs/framework/solid/reference/useMutation.md index c91bac8d6b7..0b0d99b9892 100644 --- a/docs/framework/solid/reference/useMutation.md +++ b/docs/framework/solid/reference/useMutation.md @@ -1,11 +1,161 @@ --- id: useMutation title: useMutation -ref: docs/framework/react/reference/useMutation.md -replace: - { - '@tanstack/react-query': '@tanstack/solid-query', - 'useMutationState[(]': 'useMutationState(() => ', - 'useMutation[(]': 'useMutation(() => ', - } --- + +```tsx +const { + data, + error, + isError, + isIdle, + isPending, + isPaused, + isSuccess, + failureCount, + failureReason, + mutate, + mutateAsync, + reset, + status, + submittedAt, + variables, +} = useMutation( + () => ({ + mutationFn, + gcTime, + meta, + mutationKey, + networkMode, + onError, + onMutate, + onSettled, + onSuccess, + retry, + retryDelay, + scope, + throwOnError, + }), + () => queryClient, +) + +mutate(variables, { + onError, + onSettled, + onSuccess, +}) +``` + +**Parameter1 (Options)** + +- `mutationFn: (variables: TVariables, context: MutationFunctionContext) => Promise` + - **Required, but only if no default mutation function has been defined** + - A function that performs an asynchronous task and returns a promise. + - `variables` is an object that `mutate` will pass to your `mutationFn` + - `context` is an object that `mutate` will pass to your `mutationFn`. Contains reference to `QueryClient`, `mutationKey` and optional `meta` object. +- `gcTime: number | Infinity` + - The time in milliseconds that unused/inactive cache data remains in memory. When a mutation's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used. + - If set to `Infinity`, will disable garbage collection + - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider). +- `mutationKey: unknown[]` + - Optional + - A mutation key can be set to inherit defaults set with `queryClient.setMutationDefaults`. +- `networkMode: 'online' | 'always' | 'offlineFirst'` + - Optional + - defaults to `'online'` + - see [Network Mode](../guides/network-mode.md) for more information. +- `onMutate: (variables: TVariables, context: MutationFunctionContext) => Promise | TOnMutateResult | void` + - Optional + - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive + - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds + - The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates. +- `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire when the mutation is successful and will be passed the mutation's result. + - If a promise is returned, it will be awaited and resolved before proceeding +- `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire if the mutation encounters an error and will be passed the error. + - If a promise is returned, it will be awaited and resolved before proceeding +- `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error + - If a promise is returned, it will be awaited and resolved before proceeding +- `retry: boolean | number | (failureCount: number, error: TError) => boolean` + - Defaults to `0`. + - If `false`, failed mutations will not retry. + - If `true`, failed mutations will retry infinitely. + - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. +- `retryDelay: number | (retryAttempt: number, error: TError) => number` + - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. + - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. + - A function like `attempt => attempt * 1000` applies linear backoff. +- `scope: { id: string }` + - Optional + - Defaults to a unique id (so that all mutations run in parallel) + - Mutations with the same scope id will run in serial +- `throwOnError: undefined | boolean | (error: TError) => boolean` + - Set this to `true` if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary + - Set this to `false` to disable the behavior of throwing errors to the error boundary. + - If set to a function, it will be passed the error and should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`) +- `meta: Record` + - Optional + - If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`). + +**Parameter2 (QueryClient)** + +- `queryClient?: Accessor` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void` + - The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. + - `variables: TVariables` + - Optional + - The variables object to pass to the `mutationFn`. + - `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire when the mutation is successful and will be passed the mutation's result. + - Void function, the returned value will be ignored + - `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire if the mutation encounters an error and will be passed the error. + - Void function, the returned value will be ignored + - `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error + - Void function, the returned value will be ignored + - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. +- `mutateAsync: (variables: TVariables, { onSuccess, onSettled, onError }) => Promise` + - Similar to `mutate` but returns a promise which can be awaited. +- `status: MutationStatus` + - Will be: + - `idle` initial status prior to the mutation function executing. + - `pending` if the mutation is currently executing. + - `error` if the last mutation attempt resulted in an error. + - `success` if the last mutation attempt was successful. +- `isIdle`, `isPending`, `isSuccess`, `isError`: boolean variables derived from `status` +- `isPaused: boolean` + - will be `true` if the mutation has been `paused` + - see [Network Mode](../guides/network-mode.md) for more information. +- `data: TData | undefined` + - Defaults to `undefined` + - The last successfully resolved data for the mutation. +- `error: null | TError` + - The error object for the mutation, if an error was encountered. +- `reset: () => void` + - A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). +- `failureCount: number` + - The failure count for the mutation. + - Incremented every time the mutation fails. + - Reset to `0` when the mutation succeeds. +- `failureReason: null | TError` + - The failure reason for the mutation retry. + - Reset to `null` when the mutation succeeds. +- `submittedAt: number` + - The timestamp for when the mutation was submitted. + - Defaults to `0`. +- `variables: undefined | TVariables` + - The `variables` object passed to the `mutationFn`. + - Defaults to `undefined`. diff --git a/docs/framework/solid/reference/useMutationState.md b/docs/framework/solid/reference/useMutationState.md index 57775a88255..c0dbe13af99 100644 --- a/docs/framework/solid/reference/useMutationState.md +++ b/docs/framework/solid/reference/useMutationState.md @@ -1,11 +1,84 @@ --- id: useMutationState title: useMutationState -ref: docs/framework/react/reference/useMutationState.md -replace: - { - '@tanstack/react-query': '@tanstack/solid-query', - 'useMutationState[(]': 'useMutationState(() => ', - 'useMutation[(]': 'useMutation(() => ', - } --- + +`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state. + +**Example 1: Get all variables of all running mutations** + +```tsx +import { useMutationState } from '@tanstack/solid-query' + +const variables = useMutationState(() => ({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, +})) + +// Access the current variables +variables() +``` + +**Example 2: Get all data for specific mutations via the `mutationKey`** + +```tsx +import { useMutation, useMutationState } from '@tanstack/solid-query' + +const mutationKey = ['posts'] + +// Some mutation that we want to get the state for +const mutation = useMutation(() => ({ + mutationKey, + mutationFn: (newPost) => { + return axios.post('/posts', newPost) + }, +})) + +const data = useMutationState(() => ({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey }, + select: (mutation) => mutation.state.data, +})) +``` + +**Example 3: Access the latest mutation data via the `mutationKey`**. +Each invocation of `mutate` adds a new entry to the mutation cache for `gcTime` milliseconds. + +To access the latest invocation, you can check for the last item that `useMutationState` returns. + +```tsx +import { useMutation, useMutationState } from '@tanstack/solid-query' + +const mutationKey = ['posts'] + +// Some mutation that we want to get the state for +const mutation = useMutation(() => ({ + mutationKey, + mutationFn: (newPost) => { + return axios.post('/posts', newPost) + }, +})) + +const data = useMutationState(() => ({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey }, + select: (mutation) => mutation.state.data, +})) + +// Latest mutation data +const latest = data()[data().length - 1] +``` + +**Options** + +- `options` + - `filters?: MutationFilters`: [Mutation Filters](../guides/filters.md#mutation-filters) + - `select?: (mutation: Mutation) => TResult` + - Use this to transform the mutation state. +- `queryClient?: Accessor` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `Accessor>` + - Will resolve to an Array of whatever `select` returns for each matching mutation. diff --git a/docs/framework/solid/reference/useQueries.md b/docs/framework/solid/reference/useQueries.md index 4233cfeef94..0dd688de8f6 100644 --- a/docs/framework/solid/reference/useQueries.md +++ b/docs/framework/solid/reference/useQueries.md @@ -1,10 +1,143 @@ --- id: useQueries title: useQueries -ref: docs/framework/react/reference/useQueries.md -replace: - { - '@tanstack/react-query': '@tanstack/solid-query', - 'useQueries[(]': 'useQueries(() => ', - } --- + +The `useQueries` hook can be used to fetch a variable number of queries: + +```tsx +const ids = [1, 2, 3] +const results = useQueries(() => ({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + staleTime: Infinity, + })), +})) +``` + +**Options** + +The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](./useQuery.md) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level). + +- `queryClient?: QueryClient` + - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used. +- `combine?: (result: UseQueriesResults) => TCombinedResult` + - Use this to combine the results of the queries into a single value. + +> Having the same query key more than once in the array of query objects may cause some data to be shared between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired structure. + +**placeholderData** + +The `placeholderData` option exists for `useQueries` as well, but it doesn't get information passed from previously rendered Queries like `useQuery` does, because the input to `useQueries` can be a different number of Queries on each render. + +**Returns** + +The `useQueries` hook returns an array with all the query results. The order returned is the same as the input order. + +## Combine + +If you want to combine `data` (or other Query information) from the results into a single value, you can use the `combine` option. The result will be structurally shared to be as referentially stable as possible. + +```tsx +const ids = [1, 2, 3] +const combinedQueries = useQueries(() => ({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + combine: (results) => { + return { + data: results.map((result) => result.data), + pending: results.some((result) => result.isPending), + } + }, +})) +``` + +In the above example, `combinedQueries` will be an object with a `data` and a `pending` property. Note that all other properties of the Query results will be lost. + +### Memoization + +The `combine` function will only re-run if: + +- the `combine` function itself changed referentially +- any of the query results changed + +This means that an inlined `combine` function, as shown above, gets a new reference every time the options accessor re-evaluates. To avoid this, define `combine` as a stable function outside the accessor. + +## TypeScript: typing the `select` option + +Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls back to `unknown`. This is a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). + +```tsx +useQueries(() => ({ + queries: [ + { + queryKey: ['post', 1], + queryFn: () => fetchPost(1), + // ❌ `data` is `unknown` here + select: (data) => data.title, + }, + ], +})) +``` + +There are two supported workarounds: + +1. Annotate the `select` parameter explicitly: + +```tsx +useQueries(() => ({ + queries: [ + { + queryKey: ['post', 1], + queryFn: () => fetchPost(1), + // ✅ `data` is `Post` + select: (data: Post) => data.title, + }, + ], +})) +``` + +2. Define the query with the [`queryOptions`](./queryOptions.md) helper, which resolves its types in a single object _before_ it reaches `useQueries`: + +```tsx +const postOptions = (id: number) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + // ✅ `data` is `Post` + select: (data) => data.title, + }) + +useQueries(() => ({ queries: [postOptions(1), postOptions(2)] })) +``` + +The same limitation applies when you spread a `queryOptions` result to override its `select` inline — the overriding `select` still falls back to `unknown`: + +```tsx +useQueries(() => ({ + queries: [ + { + ...postOptions(1), + // ❌ `data` is `unknown` here + select: (data) => data.title, + }, + ], +})) +``` + +Wrap the spread in `queryOptions` again so the override is resolved before it reaches `useQueries`: + +```tsx +useQueries(() => ({ + queries: [ + queryOptions({ + ...postOptions(1), + // ✅ `data` is `Post` + select: (data) => data.title, + }), + ], +})) +``` diff --git a/docs/framework/vue/reference/hydration.md b/docs/framework/vue/reference/hydration.md index f4955994b2e..87c69c4f615 100644 --- a/docs/framework/vue/reference/hydration.md +++ b/docs/framework/vue/reference/hydration.md @@ -1,9 +1,98 @@ --- id: hydration title: hydration -ref: docs/framework/react/reference/hydration.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- -[//]: # 'HydrationBoundary' -[//]: # 'HydrationBoundary' +## `dehydrate` + +`dehydrate` creates a frozen representation of a `cache` that can later be hydrated with `hydrate`. This is useful for passing prefetched queries from server to client or persisting queries to localStorage or other persistent locations. It only includes currently successful queries by default. + +```ts +import { dehydrate } from '@tanstack/vue-query' + +const dehydratedState = dehydrate(queryClient, { + shouldDehydrateQuery, + shouldDehydrateMutation, +}) +``` + +**Options** + +- `client: QueryClient` + - **Required** + - The `queryClient` that should be dehydrated +- `options: DehydrateOptions` + - Optional + - `shouldDehydrateMutation: (mutation: Mutation) => boolean` + - Optional + - Whether to dehydrate mutations. + - The function is called for each mutation in the cache + - Return `true` to include this mutation in dehydration, or `false` otherwise + - Defaults to only including paused mutations + - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateMutation` as part of the return statement + - `shouldDehydrateQuery: (query: Query) => boolean` + - Optional + - Whether to dehydrate queries. + - The function is called for each query in the cache + - Return `true` to include this query in dehydration, or `false` otherwise + - Defaults to only including successful queries + - If you would like to extend the function while retaining the default behavior, import and execute `defaultShouldDehydrateQuery` as part of the return statement + - `serializeData?: (data: any) => any` A function to transform (serialize) data during dehydration. + - `shouldRedactErrors?: (error: unknown) => boolean` + - Optional + - Only applies to queries that are still `pending` at dehydration time — their promise is dehydrated too, and this function decides whether to redact the error if that promise later rejects. + - The function is called with that rejection error + - Return `true` to redact it, or `false` otherwise + - Defaults to redacting all such errors + - Does **not** apply to `query.state.error` on already-settled queries — that error is included in the dehydrated state as-is, so sanitize it yourself via `shouldDehydrateQuery` if it may contain sensitive data + +**Returns** + +- `dehydratedState: DehydratedState` + - This includes everything that is needed to hydrate the `queryClient` at a later point + - You **should not** rely on the exact format of this response, it is not part of the public API and can change at any time + - This result is not in serialized form, you need to do that yourself if desired + +### Limitations + +Some storage systems (such as browser [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)) require values to be JSON serializable. If you need to dehydrate values that are not automatically serializable to JSON (like `Error` or `undefined`), you have to serialize them for yourself. Since only successful queries are included per default, to also include `Errors`, you have to provide `shouldDehydrateQuery`, e.g.: + +```ts +// server +const state = dehydrate(client, { shouldDehydrateQuery: () => true }) // to also include Errors +const serializedState = mySerialize(state) // transform Error instances to objects + +// client +const state = myDeserialize(serializedState) // transform objects back to Error instances +hydrate(client, state) +``` + +## `hydrate` + +`hydrate` adds a previously dehydrated state into a `cache`. + +```ts +import { hydrate } from '@tanstack/vue-query' + +hydrate(queryClient, dehydratedState, options) +``` + +**Options** + +- `client: QueryClient` + - **Required** + - The `queryClient` to hydrate the state into +- `dehydratedState: DehydratedState` + - **Required** + - The state to hydrate into the client +- `options: HydrateOptions` + - Optional + - `defaultOptions: DefaultOptions` + - Optional + - `mutations: MutationOptions` The default mutation options to use for the hydrated mutations. + - `queries: QueryOptions` The default query options to use for the hydrated queries. + - `deserializeData?: (data: any) => any` A function to transform (deserialize) data before it is put into the cache. + +### Limitations + +If the queries you're trying to hydrate already exist in the queryCache, `hydrate` will only overwrite them if the data is newer than the data present in the cache. Otherwise, it will **not** get applied. diff --git a/docs/framework/vue/reference/infiniteQueryOptions.md b/docs/framework/vue/reference/infiniteQueryOptions.md index fa4b38aae98..5455c2a440f 100644 --- a/docs/framework/vue/reference/infiniteQueryOptions.md +++ b/docs/framework/vue/reference/infiniteQueryOptions.md @@ -1,5 +1,21 @@ --- id: infiniteQueryOptions title: infiniteQueryOptions -ref: docs/framework/react/reference/infiniteQueryOptions.md --- + +```tsx +infiniteQueryOptions({ + queryKey, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to [`useInfiniteQuery`](./useInfiniteQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + +- `queryKey: QueryKey` + - **Required** + - The query key to generate options for. + +See [useInfiniteQuery](./useInfiniteQuery.md) for more information. diff --git a/docs/framework/vue/reference/mutationOptions.md b/docs/framework/vue/reference/mutationOptions.md index b34296ad545..0fa145a890f 100644 --- a/docs/framework/vue/reference/mutationOptions.md +++ b/docs/framework/vue/reference/mutationOptions.md @@ -1,5 +1,15 @@ --- id: mutationOptions title: mutationOptions -ref: docs/framework/react/reference/mutationOptions.md --- + +```tsx +mutationOptions({ + mutationFn, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `mutationOptions` that you can also pass to [`useMutation`](./useMutation.md). diff --git a/docs/framework/vue/reference/queryOptions.md b/docs/framework/vue/reference/queryOptions.md index 401cf8d1043..f6f0ac7f2e9 100644 --- a/docs/framework/vue/reference/queryOptions.md +++ b/docs/framework/vue/reference/queryOptions.md @@ -1,5 +1,26 @@ --- id: queryOptions title: queryOptions -ref: docs/framework/react/reference/queryOptions.md --- + +```tsx +queryOptions({ + queryKey, + ...options, +}) +``` + +**Options** + +You can generally pass everything to `queryOptions` that you can also pass to [`useQuery`](./useQuery.md). These options can be shared across hooks and imperative APIs such as `queryClient.query`. + +- `queryKey: QueryKey` + - **Required** + - The query key to generate options for. +[//]: # 'Materials' + +## Further reading + +To learn more about `QueryOptions`, have a look at [this article by TkDodo The Query Options API](https://tkdodo.eu/blog/the-query-options-api). + +[//]: # 'Materials' diff --git a/docs/framework/vue/reference/useInfiniteQuery.md b/docs/framework/vue/reference/useInfiniteQuery.md index 41501810315..f7bcaa12043 100644 --- a/docs/framework/vue/reference/useInfiniteQuery.md +++ b/docs/framework/vue/reference/useInfiniteQuery.md @@ -1,9 +1,88 @@ --- id: useInfiniteQuery title: useInfiniteQuery -ref: docs/framework/react/reference/useInfiniteQuery.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- -[//]: # 'ReactUse' -[//]: # 'ReactUse' +```tsx +const { + fetchNextPage, + fetchPreviousPage, + hasNextPage, + hasPreviousPage, + isFetchingNextPage, + isFetchingPreviousPage, + ...result +} = useInfiniteQuery({ + queryKey, + queryFn: ({ pageParam }) => fetchPage(pageParam), + initialPageParam: 1, + ...options, + getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => + lastPage.nextCursor, + getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => + firstPage.prevCursor, +}) +``` + +**Options** + +The options for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md) with the addition of the following: + +- `queryFn: (context: QueryFunctionContext) => Promise` + - **Required, but only if no default query function has been defined** [`defaultQueryFn`](../guides/default-query-function.md) + - The function that the query will use to request data. + - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext) + - Must return a promise that will either resolve data or throw an error. +- `initialPageParam: TPageParam` + - **Required** + - The default page param to use when fetching the first page. +- `getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null` + - **Required** + - When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. + - It should return a **single variable** that will be passed as `pageParam` on your query function's context object (e.g. `queryFn: ({ pageParam }) => ...`). + - Return `undefined` or `null` to indicate there is no next page available. +- `getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined | null` + - When new data is received for this query, this function receives both the first page of the infinite list of data and the full array of all pages, as well as pageParam information. + - It should return a **single variable** that will be passed as `pageParam` on your query function's context object (e.g. `queryFn: ({ pageParam }) => ...`). + - Return `undefined` or `null`to indicate there is no previous page available. +- `maxPages: number | undefined` + - The maximum number of pages to store in the infinite query data. + - When the maximum number of pages is reached, fetching a new page will result in the removal of either the first or last page from the pages array, depending on the specified direction. + - If `undefined` or equals `0`, the number of pages is unlimited + - Default value is `undefined` + - `getNextPageParam` and `getPreviousPageParam` must be properly defined if `maxPages` value is greater than `0` to allow fetching a page in both directions when needed. + +**Returns** + +The returned properties for `useInfiniteQuery` are identical to the [`useQuery` hook](../reference/useQuery.md), with the addition of the following properties and a small difference in `isRefetching` and `isRefetchError`: + +- `data.pages: TData[]` + - Array containing all pages. +- `data.pageParams: unknown[]` + - Array containing all page params. +- `isFetchingNextPage: boolean` + - Will be `true` while fetching the next page with `fetchNextPage`. +- `isFetchingPreviousPage: boolean` + - Will be `true` while fetching the previous page with `fetchPreviousPage`. +- `fetchNextPage: (options?: FetchNextPageOptions) => Promise` + - This function allows you to fetch the next "page" of results. + - `options.cancelRefetch: boolean` if set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, whether the previous + invocation has resolved or not. Also, the result from previous invocations will be ignored. If set to `false`, calling `fetchNextPage` + repeatedly won't have any effect until the first invocation has resolved. Default is `true`. +- `fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise` + - This function allows you to fetch the previous "page" of results. + - `options.cancelRefetch: boolean` same as for `fetchNextPage`. +- `hasNextPage: boolean` + - Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). +- `hasPreviousPage: boolean` + - Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). +- `isFetchNextPageError: boolean` + - Will be `true` if the query failed while fetching the next page. +- `isFetchPreviousPageError: boolean` + - Will be `true` if the query failed while fetching the previous page. +- `isRefetching: boolean` + - Will be `true` whenever a background refetch is in-flight, which _does not_ include initial `pending` or fetching of next or previous page + - Is the same as `isFetching && !isPending && !isFetchingNextPage && !isFetchingPreviousPage` +- `isRefetchError: boolean` + - Will be `true` if the query failed while refetching a page. +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behaviour, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like `hasNextPage && !isFetching`. diff --git a/docs/framework/vue/reference/useIsFetching.md b/docs/framework/vue/reference/useIsFetching.md index aa1ecd221c9..e0537f0e4cb 100644 --- a/docs/framework/vue/reference/useIsFetching.md +++ b/docs/framework/vue/reference/useIsFetching.md @@ -1,6 +1,25 @@ --- id: useIsFetching title: useIsFetching -ref: docs/framework/react/reference/useIsFetching.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators). + +```tsx +import { useIsFetching } from '@tanstack/vue-query' +// How many queries are fetching? +const isFetching = useIsFetching() +// How many queries matching the posts prefix are fetching? +const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) +``` + +**Options** + +- `filters?: QueryFilters`: [Query Filters](../guides/filters.md#query-filters) +- `queryClient?: QueryClient` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `isFetching: number` + - Will be the `number` of the queries that your application is currently loading or fetching in the background. diff --git a/docs/framework/vue/reference/useIsMutating.md b/docs/framework/vue/reference/useIsMutating.md index d05d7ef67d0..2e415616918 100644 --- a/docs/framework/vue/reference/useIsMutating.md +++ b/docs/framework/vue/reference/useIsMutating.md @@ -1,6 +1,25 @@ --- id: useIsMutating title: useIsMutating -ref: docs/framework/react/reference/useIsMutating.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +`useIsMutating` is an optional hook that returns the `number` of mutations that your application is currently in a `pending` state with (useful for app-wide loading indicators). + +```tsx +import { useIsMutating } from '@tanstack/vue-query' +// How many mutations are pending? +const isMutating = useIsMutating() +// How many mutations matching the posts prefix are pending? +const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) +``` + +**Options** + +- `filters?: MutationFilters`: [Mutation Filters](../guides/filters.md#mutation-filters) +- `queryClient?: QueryClient` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `isMutating: Ref` + - Will resolve to the `number` of the mutations that your application is currently pending with. diff --git a/docs/framework/vue/reference/useMutation.md b/docs/framework/vue/reference/useMutation.md index ee5b243c252..6d98a21ae5e 100644 --- a/docs/framework/vue/reference/useMutation.md +++ b/docs/framework/vue/reference/useMutation.md @@ -1,6 +1,161 @@ --- id: useMutation title: useMutation -ref: docs/framework/react/reference/useMutation.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +```tsx +const { + data, + error, + isError, + isIdle, + isPending, + isPaused, + isSuccess, + failureCount, + failureReason, + mutate, + mutateAsync, + reset, + status, + submittedAt, + variables, +} = useMutation( + { + mutationFn, + gcTime, + meta, + mutationKey, + networkMode, + onError, + onMutate, + onSettled, + onSuccess, + retry, + retryDelay, + scope, + throwOnError, + }, + queryClient, +) + +mutate(variables, { + onError, + onSettled, + onSuccess, +}) +``` + +**Parameter1 (Options)** + +- `mutationFn: (variables: TVariables, context: MutationFunctionContext) => Promise` + - **Required, but only if no default mutation function has been defined** + - A function that performs an asynchronous task and returns a promise. + - `variables` is an object that `mutate` will pass to your `mutationFn` + - `context` is an object that `mutate` will pass to your `mutationFn`. Contains reference to `QueryClient`, `mutationKey` and optional `meta` object. +- `gcTime: number | Infinity` + - The time in milliseconds that unused/inactive cache data remains in memory. When a mutation's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used. + - If set to `Infinity`, will disable garbage collection + - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider). +- `mutationKey: unknown[]` + - Optional + - A mutation key can be set to inherit defaults set with `queryClient.setMutationDefaults`. +- `networkMode: 'online' | 'always' | 'offlineFirst'` + - Optional + - defaults to `'online'` + - see [Network Mode](../guides/network-mode.md) for more information. +- `onMutate: (variables: TVariables, context: MutationFunctionContext) => Promise | TOnMutateResult | void` + - Optional + - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive + - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds + - The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates. +- `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire when the mutation is successful and will be passed the mutation's result. + - If a promise is returned, it will be awaited and resolved before proceeding +- `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire if the mutation encounters an error and will be passed the error. + - If a promise is returned, it will be awaited and resolved before proceeding +- `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => Promise | unknown` + - Optional + - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error + - If a promise is returned, it will be awaited and resolved before proceeding +- `retry: boolean | number | (failureCount: number, error: TError) => boolean` + - Defaults to `0`. + - If `false`, failed mutations will not retry. + - If `true`, failed mutations will retry infinitely. + - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. +- `retryDelay: number | (retryAttempt: number, error: TError) => number` + - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. + - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. + - A function like `attempt => attempt * 1000` applies linear backoff. +- `scope: { id: string }` + - Optional + - Defaults to a unique id (so that all mutations run in parallel) + - Mutations with the same scope id will run in serial +- `throwOnError: undefined | boolean | (error: TError) => boolean` + - Set this to `true` if you want mutation errors to be thrown in the render phase and propagate to the nearest error boundary + - Set this to `false` to disable the behavior of throwing errors to the error boundary. + - If set to a function, it will be passed the error and should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`) +- `meta: Record` + - Optional + - If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`). + +**Parameter2 (QueryClient)** + +- `queryClient?: QueryClient` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `mutate: (variables: TVariables, options?: { onSuccess, onSettled, onError }) => void` + - The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. + - `variables: TVariables` + - Optional + - The variables object to pass to the `mutationFn`. + - `onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire when the mutation is successful and will be passed the mutation's result. + - Void function, the returned value will be ignored + - `onError: (err: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire if the mutation encounters an error and will be passed the error. + - Void function, the returned value will be ignored + - `onSettled: (data: TData | undefined, error: TError | null, variables: TVariables, onMutateResult: TOnMutateResult | undefined, context: MutationFunctionContext) => void` + - Optional + - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error + - Void function, the returned value will be ignored + - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. +- `mutateAsync: (variables: TVariables, options?: { onSuccess, onSettled, onError }) => Promise` + - Similar to `mutate` but returns a promise which can be awaited. +- `status: MutationStatus` + - Will be: + - `idle` initial status prior to the mutation function executing. + - `pending` if the mutation is currently executing. + - `error` if the last mutation attempt resulted in an error. + - `success` if the last mutation attempt was successful. +- `isIdle`, `isPending`, `isSuccess`, `isError`: boolean variables derived from `status` +- `isPaused: boolean` + - will be `true` if the mutation has been `paused` + - see [Network Mode](../guides/network-mode.md) for more information. +- `data: TData | undefined` + - Defaults to `undefined` + - The last successfully resolved data for the mutation. +- `error: null | TError` + - The error object for the mutation, if an error was encountered. +- `reset: () => void` + - A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). +- `failureCount: number` + - The failure count for the mutation. + - Incremented every time the mutation fails. + - Reset to `0` when the mutation succeeds. +- `failureReason: null | TError` + - The failure reason for the mutation retry. + - Reset to `null` when the mutation succeeds. +- `submittedAt: number` + - The timestamp for when the mutation was submitted. + - Defaults to `0`. +- `variables: undefined | TVariables` + - The `variables` object passed to the `mutationFn`. + - Defaults to `undefined`. diff --git a/docs/framework/vue/reference/useMutationState.md b/docs/framework/vue/reference/useMutationState.md index 82c0028f826..0fcdfe7e25b 100644 --- a/docs/framework/vue/reference/useMutationState.md +++ b/docs/framework/vue/reference/useMutationState.md @@ -1,6 +1,81 @@ --- id: useMutationState title: useMutationState -ref: docs/framework/react/reference/useMutationState.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state. + +**Example 1: Get all variables of all running mutations** + +```tsx +import { useMutationState } from '@tanstack/vue-query' + +const variables = useMutationState({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, +}) +``` + +**Example 2: Get all data for specific mutations via the `mutationKey`** + +```tsx +import { useMutation, useMutationState } from '@tanstack/vue-query' + +const mutationKey = ['posts'] + +// Some mutation that we want to get the state for +const mutation = useMutation({ + mutationKey, + mutationFn: (newPost) => { + return axios.post('/posts', newPost) + }, +}) + +const data = useMutationState({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey }, + select: (mutation) => mutation.state.data, +}) +``` + +**Example 3: Access the latest mutation data via the `mutationKey`**. +Each invocation of `mutate` adds a new entry to the mutation cache for `gcTime` milliseconds. + +To access the latest invocation, you can check for the last item that `useMutationState` returns. + +```tsx +import { useMutation, useMutationState } from '@tanstack/vue-query' + +const mutationKey = ['posts'] + +// Some mutation that we want to get the state for +const mutation = useMutation({ + mutationKey, + mutationFn: (newPost) => { + return axios.post('/posts', newPost) + }, +}) + +const data = useMutationState({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey }, + select: (mutation) => mutation.state.data, +}) + +// Latest mutation data +const latest = data.value[data.value.length - 1] +``` + +**Options** + +- `options` + - `filters?: MutationFilters`: [Mutation Filters](../guides/filters.md#mutation-filters) + - `select?: (mutation: Mutation) => TResult` + - Use this to transform the mutation state. +- `queryClient?: QueryClient` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `Array` + - Will be an Array of whatever `select` returns for each matching mutation. diff --git a/docs/framework/vue/reference/usePrefetchInfiniteQuery.md b/docs/framework/vue/reference/usePrefetchInfiniteQuery.md index c7af728d36d..125a6605be1 100644 --- a/docs/framework/vue/reference/usePrefetchInfiniteQuery.md +++ b/docs/framework/vue/reference/usePrefetchInfiniteQuery.md @@ -1,6 +1,33 @@ --- id: usePrefetchInfiniteQuery title: usePrefetchInfiniteQuery -ref: docs/framework/react/reference/usePrefetchInfiniteQuery.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +```tsx +usePrefetchInfiniteQuery(options) +``` + +**Options** + +You can pass everything to `usePrefetchInfiniteQuery` that you can pass to [`queryClient.infiniteQuery`](../../../reference/QueryClient.md#queryclient-infinitequery). Remember that some of them are required as below: + +- `queryKey: QueryKey` + - **Required** + - The query key to prefetch during render + +- `queryFn: (context: QueryFunctionContext) => Promise` + - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. + +- `initialPageParam: TPageParam` + - **Required** + - The default page param to use when fetching the first page. + +- `getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null` + - **Required** + - When new data is received for this query, this function receives both the last page of the infinite list of data and the full array of all pages, as well as pageParam information. + - It should return a **single variable** that will be passed as the last optional parameter to your query function. + - Return `undefined` or `null` to indicate there is no next page available. + +- **Returns** + +The `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, before a suspense boundary that wraps a component using `useInfiniteQuery`'s `suspense()` — see the [Suspense guide](../guides/suspense.md). diff --git a/docs/framework/vue/reference/usePrefetchQuery.md b/docs/framework/vue/reference/usePrefetchQuery.md index e518a62ef84..dd51f44e54c 100644 --- a/docs/framework/vue/reference/usePrefetchQuery.md +++ b/docs/framework/vue/reference/usePrefetchQuery.md @@ -1,6 +1,23 @@ --- id: usePrefetchQuery title: usePrefetchQuery -ref: docs/framework/react/reference/usePrefetchQuery.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +```tsx +usePrefetchQuery(options) +``` + +**Options** + +You can pass everything to `usePrefetchQuery` that you can pass to [`queryClient.query`](../../../reference/QueryClient.md#queryclient-query). Remember that some of them are required as below: + +- `queryKey: QueryKey` + - **Required** + - The query key to prefetch during render + +- `queryFn: (context: QueryFunctionContext) => TQueryFnData | Promise` + - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. + +**Returns** + +The `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before a suspense boundary that wraps a component using `useQuery`'s `suspense()` — see the [Suspense guide](../guides/suspense.md). diff --git a/docs/framework/vue/reference/useQueries.md b/docs/framework/vue/reference/useQueries.md index a5cb5ad64c1..94a0bf01913 100644 --- a/docs/framework/vue/reference/useQueries.md +++ b/docs/framework/vue/reference/useQueries.md @@ -1,6 +1,146 @@ --- id: useQueries title: useQueries -ref: docs/framework/react/reference/useQueries.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +The `useQueries` hook can be used to fetch a variable number of queries: + +```tsx +const ids = [1, 2, 3] +const results = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + staleTime: Infinity, + })), +}) + +// `results` is a readonly ref — unwrap it to access the array +results.value +``` + +**Options** + +The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](./useQuery.md) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level). + +- `queryClient?: QueryClient` + - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used. +- `combine?: (result: UseQueriesResults) => TCombinedResult` + - Use this to combine the results of the queries into a single value. + +> Having the same query key more than once in the array of query objects may cause some data to be shared between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired structure. + +**placeholderData** + +The `placeholderData` option exists for `useQueries` as well, but it doesn't get information passed from previously rendered Queries like `useQuery` does, because the input to `useQueries` can be a different number of Queries on each render. + +**Returns** + +The `useQueries` hook returns a readonly ref whose `.value` is an array with all the query results. The order returned is the same as the input order. + +## Combine + +If you want to combine `data` (or other Query information) from the results into a single value, you can use the `combine` option. The result will be structurally shared to be as referentially stable as possible. + +```tsx +const ids = [1, 2, 3] +const combinedQueries = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + combine: (results) => { + return { + data: results.map((result) => result.data), + pending: results.some((result) => result.isPending), + } + }, +}) +``` + +In the above example, `combinedQueries.value` will be an object with a `data` and a `pending` property. Note that all other properties of the Query results will be lost. + +### Memoization + +The `combine` function will only re-run if: + +- the `combine` function itself changed referentially +- any of the query results changed + +Unlike React, a Vue `setup()` function only runs once per component instance, so an inlined `combine` function, as shown above, already has a stable reference across reactive updates — no extra memoization is needed. + +## TypeScript: typing the `select` option + +Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls back to `unknown`. This is a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). + +```tsx +useQueries({ + queries: [ + { + queryKey: ['post', 1], + queryFn: () => fetchPost(1), + // ❌ `data` is `unknown` here + select: (data) => data.title, + }, + ], +}) +``` + +There are two supported workarounds: + +1. Annotate the `select` parameter explicitly: + +```tsx +useQueries({ + queries: [ + { + queryKey: ['post', 1], + queryFn: () => fetchPost(1), + // ✅ `data` is `Post` + select: (data: Post) => data.title, + }, + ], +}) +``` + +2. Define the query with the [`queryOptions`](./queryOptions.md) helper, which resolves its types in a single object _before_ it reaches `useQueries`: + +```tsx +const postOptions = (id: number) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + // ✅ `data` is `Post` + select: (data) => data.title, + }) + +useQueries({ queries: [postOptions(1), postOptions(2)] }) +``` + +The same limitation applies when you spread a `queryOptions` result to override its `select` inline — the overriding `select` still falls back to `unknown`: + +```tsx +useQueries({ + queries: [ + { + ...postOptions(1), + // ❌ `data` is `unknown` here + select: (data) => data.title, + }, + ], +}) +``` + +Wrap the spread in `queryOptions` again so the override is resolved before it reaches `useQueries`: + +```tsx +useQueries({ + queries: [ + queryOptions({ + ...postOptions(1), + // ✅ `data` is `Post` + select: (data) => data.title, + }), + ], +}) +``` diff --git a/docs/framework/vue/reference/useQuery.md b/docs/framework/vue/reference/useQuery.md index 151370c6537..9ffb86cdd1c 100644 --- a/docs/framework/vue/reference/useQuery.md +++ b/docs/framework/vue/reference/useQuery.md @@ -1,6 +1,258 @@ --- id: useQuery title: useQuery -ref: docs/framework/react/reference/useQuery.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +```tsx +const { + data, + dataUpdatedAt, + error, + errorUpdateCount, + errorUpdatedAt, + failureCount, + failureReason, + fetchStatus, + isError, + isFetched, + isFetchedAfterMount, + isFetching, + isInitialLoading, + isLoading, + isLoadingError, + isPaused, + isPending, + isPlaceholderData, + isRefetchError, + isRefetching, + isStale, + isSuccess, + isEnabled, + refetch, + status, +} = useQuery( + { + queryKey, + queryFn, + gcTime, + enabled, + networkMode, + initialData, + initialDataUpdatedAt, + meta, + notifyOnChangeProps, + placeholderData, + queryKeyHashFn, + refetchInterval, + refetchIntervalInBackground, + refetchOnMount, + refetchOnReconnect, + refetchOnWindowFocus, + retry, + retryOnMount, + retryDelay, + select, + staleTime, + structuralSharing, + subscribed, + throwOnError, + }, + queryClient, +) +``` + +**Parameter1 (Options)** + +- `queryKey: unknown[]` + - **Required** + - The query key to use for this query. + - The query key will be hashed into a stable hash. See [Query Keys](../guides/query-keys.md) for more information. + - The query will automatically update when this key changes (as long as `enabled` is not set to `false`). +- `queryFn: (context: QueryFunctionContext) => TData | Promise` + - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information. + - The function that the query will use to request data. + - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext) + - Must return the data synchronously, or a promise that will either resolve data or throw an error. The data cannot be `undefined`. +- `enabled: boolean | (query: Query) => boolean` + - Set this to `false` to disable this query from automatically running. + - Can be used for [Dependent Queries](../guides/dependent-queries.md). +- `networkMode: 'online' | 'always' | 'offlineFirst'` + - optional + - defaults to `'online'` + - see [Network Mode](../guides/network-mode.md) for more information. +- `retry: boolean | number | (failureCount: number, error: TError) => boolean` + - If `false`, failed queries will not retry by default. + - If `true`, failed queries will retry infinitely. + - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. + - If set to a function, it will be called with `failureCount` (starting at `0` for the first retry) and `error` to determine if a retry should be attempted. + - defaults to `3` on the client and `0` on the server +- `retryOnMount: boolean | (query: Query) => boolean` + - If set to `false`, the query will not be retried on mount if it contains an error and has no data. Defaults to `true`. + - If set to a function, the function will be executed with the query to compute the value. +- `retryDelay: number | (retryAttempt: number, error: TError) => number` + - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. + - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. + - A function like `attempt => attempt * 1000` applies linear backoff. +- `staleTime: number | 'static' | ((query: Query) => number | 'static')` + - Optional + - Defaults to `0` + - The time in milliseconds after which data is considered stale. This value only applies to the hook it is defined on. + - If set to `Infinity`, the data will not be considered stale unless manually invalidated + - If set to a function, the function will be executed with the query to compute a `staleTime`. + - If set to `'static'`, the data will never be considered stale +- `gcTime: number | Infinity` + - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR + - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. + - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider). + - If set to `Infinity`, will disable garbage collection +- `queryKeyHashFn: (queryKey: QueryKey) => string` + - Optional + - If specified, this function is used to hash the `queryKey` to a string. +- `refetchInterval: number | false | ((query: Query) => number | false | undefined)` + - Optional + - If set to a number, all queries will continuously refetch at this frequency in milliseconds + - If set to a function, the function will be executed with the query to compute a frequency +- `refetchIntervalInBackground: boolean` + - Optional + - If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background +- `refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")` + - Optional + - Defaults to `true` + - If set to `true`, the query will refetch on mount if the data is stale. + - If set to `false`, the query will not refetch on mount. + - If set to `"always"`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + - If set to a function, the function will be executed with the query to compute the value +- `refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")` + - Optional + - Defaults to `true` + - If set to `true`, the query will refetch on window focus if the data is stale. + - If set to `false`, the query will not refetch on window focus. + - If set to `"always"`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + - If set to a function, the function will be executed with the query to compute the value +- `refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")` + - Optional + - Defaults to `true` + - If set to `true`, the query will refetch on reconnect if the data is stale. + - If set to `false`, the query will not refetch on reconnect. + - If set to `"always"`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + - If set to a function, the function will be executed with the query to compute the value +- `notifyOnChangeProps: string[] | "all" | (() => string[] | "all" | undefined)` + - Optional + - If set, the component will only re-render if any of the listed properties change. + - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. + - If set to `"all"`, the component will opt-out of smart tracking and re-render whenever a query is updated. + - If set to a function, the function will be executed to compute the list of properties. + - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. +- `select: (data: TData) => unknown` + - Optional + - This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache. + - The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. Since a Vue `setup()` function only runs once per component instance, an inline `select` function already has a stable reference across reactive updates. +- `initialData: TData | () => TData` + - Optional + - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) + - If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData + - Initial data is considered stale by default unless a `staleTime` has been set. + - `initialData` **is persisted** to the cache +- `initialDataUpdatedAt: number | (() => number | undefined)` + - Optional + - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. +- `placeholderData: TData | (previousValue: TData | undefined, previousQuery: Query | undefined) => TData` + - Optional + - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. + - `placeholderData` is **not persisted** to the cache + - If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. +- `structuralSharing: boolean | (oldData: unknown | undefined, newData: unknown) => unknown` + - Optional + - Defaults to `true` + - If set to `false`, structural sharing between query results will be disabled. + - If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. +- `subscribed: boolean` + - Optional + - Defaults to `true` + - If set to `false`, this instance of `useQuery` will not be subscribed to the cache. This means it won't trigger the `queryFn` on its own, and it won't receive updates if data gets into cache by other means. +- `throwOnError: undefined | boolean | (error: TError, query: Query) => boolean` + - Optional + - Defaults to `false` + - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary + - If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`) +- `meta: Record` + - Optional + - If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. + +**Parameter2 (QueryClient)** + +- `queryClient?: QueryClient` + - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `status: QueryStatus` + - Will be: + - `pending` if there's no cached data and no query attempt was finished yet. + - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch + - `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization. +- `isPending: boolean` + - A derived boolean from the `status` variable above, provided for convenience. +- `isSuccess: boolean` + - A derived boolean from the `status` variable above, provided for convenience. +- `isError: boolean` + - A derived boolean from the `status` variable above, provided for convenience. +- `isLoadingError: boolean` + - Will be `true` if the query failed while fetching for the first time. +- `isRefetchError: boolean` + - Will be `true` if the query failed while refetching. +- `data: TData` + - Defaults to `undefined`. + - The last successfully resolved data for the query. +- `dataUpdatedAt: number` + - The timestamp for when the query most recently returned the `status` as `"success"`. +- `error: null | TError` + - Defaults to `null` + - The error object for the query, if an error was thrown. +- `errorUpdatedAt: number` + - The timestamp for when the query most recently returned the `status` as `"error"`. +- `isStale: boolean` + - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. +- `isPlaceholderData: boolean` + - Will be `true` if the data shown is the placeholder data. +- `isFetched: boolean` + - Will be `true` if the query has been fetched. +- `isFetchedAfterMount: boolean` + - Will be `true` if the query has been fetched after the component mounted. + - This property can be used to not show any previously cached data. +- `fetchStatus: FetchStatus` + - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches. + - `paused`: The query wanted to fetch, but has been `paused`. + - `idle`: The query is not fetching. + - see [Network Mode](../guides/network-mode.md) for more information. +- `isFetching: boolean` + - A derived boolean from the `fetchStatus` variable above, provided for convenience. +- `isPaused: boolean` + - A derived boolean from the `fetchStatus` variable above, provided for convenience. +- `isRefetching: boolean` + - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending` + - Is the same as `isFetching && !isPending` +- `isLoading: boolean` + - Is `true` whenever the first fetch for a query is in-flight + - Is the same as `isFetching && isPending` +- `isInitialLoading: boolean` + - **deprecated** + - An alias for `isLoading`, will be removed in the next major version. +- `isEnabled: boolean` + - Is `true` if this query observer is enabled, `false` otherwise. +- `failureCount: number` + - The failure count for the query. + - Incremented every time the query fails. + - Reset to `0` when the query succeeds. +- `failureReason: null | TError` + - The failure reason for the query retry. + - Reset to `null` when the query succeeds. +- `errorUpdateCount: number` + - The sum of all errors. +- `refetch: (options?: { throwOnError?: boolean, cancelRefetch?: boolean }) => Promise` + - A function to manually refetch the query. + - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option + - `cancelRefetch?: boolean` + - Defaults to `true` + - Per default, a currently running request will be cancelled before a new request is made + - When set to `false`, no refetch will be made if there is already a request running. diff --git a/docs/framework/vue/reference/useQueryClient.md b/docs/framework/vue/reference/useQueryClient.md index 9ed6be043a4..c5029a3b59c 100644 --- a/docs/framework/vue/reference/useQueryClient.md +++ b/docs/framework/vue/reference/useQueryClient.md @@ -1,6 +1,22 @@ --- id: useQueryClient title: useQueryClient -ref: docs/framework/react/reference/useQueryClient.md -replace: { '@tanstack/react-query': '@tanstack/vue-query' } --- + +The `useQueryClient` hook returns the current `QueryClient` instance. + +```tsx +import { useQueryClient } from '@tanstack/vue-query' + +const queryClient = useQueryClient(id?: string) +``` + +**Options** + +- `id?: string` + - Use this if you have set up multiple `VueQueryPlugin` instances with different `queryClientKey`s, to select which injected `QueryClient` to use. Otherwise, the one from the nearest context will be used. + +**Returns** + +- `QueryClient` + - The injected `QueryClient` instance. Throws if none is found in context. diff --git a/docs/reference/InfiniteQueryObserver.md b/docs/reference/InfiniteQueryObserver.md index 9be871279e5..f92c373916b 100644 --- a/docs/reference/InfiniteQueryObserver.md +++ b/docs/reference/InfiniteQueryObserver.md @@ -21,4 +21,4 @@ const unsubscribe = observer.subscribe((result) => { **Options** -The options for the `InfiniteQueryObserver` are exactly the same as those of [`useInfiniteQuery`](../framework/react/reference/useInfiniteQuery). +The options for the `InfiniteQueryObserver` are exactly the same as those of [`useInfiniteQuery`](../framework/react/reference/functions/useInfiniteQuery.md). diff --git a/docs/reference/QueriesObserver.md b/docs/reference/QueriesObserver.md index f5e2a1ac21a..3ebd21af9ec 100644 --- a/docs/reference/QueriesObserver.md +++ b/docs/reference/QueriesObserver.md @@ -19,4 +19,4 @@ const unsubscribe = observer.subscribe((result) => { **Options** -The options for the `QueriesObserver` are exactly the same as those of [`useQueries`](../framework/react/reference/useQueries). +The options for the `QueriesObserver` are exactly the same as those of [`useQueries`](../framework/react/reference/functions/useQueries.md). diff --git a/docs/reference/QueryClient.md b/docs/reference/QueryClient.md index 64c91c627ed..bdc9175e551 100644 --- a/docs/reference/QueryClient.md +++ b/docs/reference/QueryClient.md @@ -57,7 +57,7 @@ Its available methods are: - `defaultOptions?: DefaultOptions` - Optional - Define defaults for all queries and mutations using this queryClient. - - You can also define defaults to be used for [hydration](../framework/react/reference/hydration.md) + - You can also define defaults to be used for [hydration](../framework/react/guides/ssr.md) ## `queryClient.query` @@ -90,7 +90,7 @@ try { **Options** -The options for `query` are exactly the same as those of [`useQuery`](../framework/react/reference/useQuery.md), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, suspense, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/TanStack/query/blob/7cd2d192e6da3df0b08e334ea1cf04cd70478827/packages/query-core/src/types.ts#L119) for more clarity. +The options for `query` are exactly the same as those of [`useQuery`](../framework/react/reference/functions/useQuery.md), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, suspense, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/TanStack/query/blob/7cd2d192e6da3df0b08e334ea1cf04cd70478827/packages/query-core/src/types.ts#L119) for more clarity. **Returns** @@ -111,7 +111,7 @@ try { **Options** -The options for `infiniteQuery` are exactly the same as those of [`query`](#queryclient-query), with the addition of `initialPageParam`, `pages` and `getNextPageParam` options from [`useInfiniteQuery`](../framework/react/reference/useInfiniteQuery.md). +The options for `infiniteQuery` are exactly the same as those of [`query`](#queryclient-query), with the addition of `initialPageParam`, `pages` and `getNextPageParam` options from [`useInfiniteQuery`](../framework/react/reference/functions/useInfiniteQuery.md). **Returns** @@ -377,7 +377,7 @@ if (queryClient.isFetching()) { } ``` -TanStack Query also exports a handy [`useIsFetching`](../framework/react/reference/useIsFetching.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache. +TanStack Query also exports a handy [`useIsFetching`](../framework/react/reference/functions/useIsFetching.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache. **Options** @@ -397,7 +397,7 @@ if (queryClient.isMutating()) { } ``` -TanStack Query also exports a handy [`useIsMutating`](../framework/react/reference/useIsMutating.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache. +TanStack Query also exports a handy [`useIsMutating`](../framework/react/reference/functions/useIsMutating.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache. **Options** diff --git a/docs/reference/QueryObserver.md b/docs/reference/QueryObserver.md index 278547a1285..8815dc3e989 100644 --- a/docs/reference/QueryObserver.md +++ b/docs/reference/QueryObserver.md @@ -16,4 +16,4 @@ const unsubscribe = observer.subscribe((result) => { **Options** -The options for the `QueryObserver` are exactly the same as those of [`useQuery`](../framework/react/reference/useQuery). +The options for the `QueryObserver` are exactly the same as those of [`useQuery`](../framework/react/reference/functions/useQuery.md). diff --git a/packages/react-query/src/infiniteQueryOptions.ts b/packages/react-query/src/infiniteQueryOptions.ts index 7bb329188b9..10898979d7b 100644 --- a/packages/react-query/src/infiniteQueryOptions.ts +++ b/packages/react-query/src/infiniteQueryOptions.ts @@ -73,7 +73,9 @@ export type UnusedSkipTokenInfiniteOptions< > & { /** * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If - * you don't intend to run the query yet, omit `queryFn` or use a default query function instead. + * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a + * fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been + * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own. */ queryFn?: Exclude< UseInfiniteQueryOptions< diff --git a/packages/react-query/src/queryOptions.ts b/packages/react-query/src/queryOptions.ts index 34917520b7c..aa824b7389b 100644 --- a/packages/react-query/src/queryOptions.ts +++ b/packages/react-query/src/queryOptions.ts @@ -58,9 +58,9 @@ export type UnusedSkipTokenOptions< > & { /** * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If - * you don't intend to run the query yet, set `enabled: false` or use a default query function instead — - * omitting `queryFn` alone still triggers a fetch that fails with "Missing queryFn" unless `enabled` is - * `false`. + * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a + * fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been + * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own. */ queryFn?: Exclude< UseQueryOptions['queryFn'], diff --git a/packages/react-query/src/useMutation.ts b/packages/react-query/src/useMutation.ts index 456a81493a0..178e95e7069 100644 --- a/packages/react-query/src/useMutation.ts +++ b/packages/react-query/src/useMutation.ts @@ -28,7 +28,8 @@ import type { DefaultError, QueryClient } from '@tanstack/query-core' * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks - * fire only for the latest call you've made. + * fire only for the latest call you've made, and only while the component is still mounted — unmounting before + * the mutation settles removes the subscription and prevents them from firing. * * @example * ```tsx