diff --git a/docs/framework/angular/reference/functions/dehydrate.md b/docs/framework/angular/reference/functions/dehydrate.md index 53b1fc5eba7..e01b3cf74ef 100644 --- a/docs/framework/angular/reference/functions/dehydrate.md +++ b/docs/framework/angular/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/angular/reference/functions/hydrate.md b/docs/framework/angular/reference/functions/hydrate.md index 5e250b9da2b..e160e90a332 100644 --- a/docs/framework/angular/reference/functions/hydrate.md +++ b/docs/framework/angular/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/angular/reference/functions/infiniteQueryOptions.md b/docs/framework/angular/reference/functions/infiniteQueryOptions.md index fea63614295..99b9c2a64fb 100644 --- a/docs/framework/angular/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/angular/reference/functions/infiniteQueryOptions.md @@ -3,6 +3,22 @@ id: infiniteQueryOptions title: infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: DefinedInitialDataInfiniteOptions): CreateInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UnusedSkipTokenInfiniteOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UndefinedInitialDataInfiniteOptions): CreateInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +- [`DefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryOptions`](#call-signature-1): You can generally pass everything to `infiniteQueryOptions` that you can also pass to `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options for. +- [`UnusedSkipTokenInfiniteOptions` → `OmitKeyof`](#call-signature-2): You can generally pass everything to `infiniteQueryOptions` that you can also pass to `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options for. +- [`UndefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryOptions`](#call-signature-3): You can generally pass everything to `infiniteQueryOptions` that you can also pass to `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options for. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -94,6 +110,8 @@ export class Projects { } ``` + + ## Call Signature ```ts @@ -189,6 +207,8 @@ export class Comments { } ``` + + ## Call Signature ```ts @@ -283,3 +303,26 @@ export class Comments { readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId())) } ``` + + + +## 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 +`injectInfiniteQuery`. + + + +#### `options` properties + +Built from [`CreateInfiniteQueryOptions`](../interfaces/CreateInfiniteQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/angular/reference/functions/injectInfiniteQuery.md b/docs/framework/angular/reference/functions/injectInfiniteQuery.md index 25fc0c0f09f..61e20feb353 100644 --- a/docs/framework/angular/reference/functions/injectInfiniteQuery.md +++ b/docs/framework/angular/reference/functions/injectInfiniteQuery.md @@ -3,6 +3,22 @@ id: injectInfiniteQuery title: injectInfiniteQuery --- +## Overview + +```ts +function injectInfiniteQuery(injectInfiniteQueryFn: () => DefinedInitialDataInfiniteOptions, options?: InjectInfiniteQueryOptions): DefinedCreateInfiniteQueryResult; +function injectInfiniteQuery(injectInfiniteQueryFn: () => UndefinedInitialDataInfiniteOptions, options?: InjectInfiniteQueryOptions): CreateInfiniteQueryResult; +function injectInfiniteQuery(injectInfiniteQueryFn: () => CreateInfiniteQueryOptions, options?: InjectInfiniteQueryOptions): CreateInfiniteQueryResult; +``` + +- [`DefinedInitialDataInfiniteOptions` → `DefinedCreateInfiniteQueryResult`](#call-signature-1): The options for `injectInfiniteQuery` are identical to `injectQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. Infinite queries can additively "load more" data onto an existing set of data, or "infinite scroll". +- [`UndefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryResult`](#call-signature-2): Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key. Infinite queries can additively "load more" data onto an existing set of data, or "infinite scroll". +- [`CreateInfiniteQueryOptions` → `CreateInfiniteQueryResult`](#call-signature-3): This overload accepts the general [CreateInfiniteQueryOptions](../interfaces/CreateInfiniteQueryOptions.md) shape rather than the `initialData`-aware overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping `injectInfiniteQuery` in your own helper function that forwards caller-provided options. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -104,6 +120,8 @@ export class Projects { } ``` + + ## Call Signature ```ts @@ -293,6 +311,8 @@ export class Comments { } ``` + + ## Call Signature ```ts @@ -348,3 +368,78 @@ Additional configuration. [`CreateInfiniteQueryResult`](../type-aliases/CreateInfiniteQueryResult.md)\<`TData`, `TError`\> The infinite query result. + + + +## Parameters + +### injectInfiniteQueryFn + +() => [`CreateInfiniteQueryOptions`](../interfaces/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +A function that returns infinite query options. Similar to `computed` from +Angular, this function runs in the reactive context, so signals read inside it drive the query. + + + +#### `injectInfiniteQueryFn` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### options? + +[`InjectInfiniteQueryOptions`](../interfaces/InjectInfiniteQueryOptions.md) + +Additional configuration. + + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the infinite query. If this is not provided, the current injection context will be used instead (via `inject`). | + + + +## Returns + +[`CreateInfiniteQueryResult`](../type-aliases/CreateInfiniteQueryResult.md)\<`TData`, `TError`\> + +The infinite query result. + + + +### Result properties + +Built from [`BaseQueryNarrowing`](../interfaces/BaseQueryNarrowing.md#properties), [`InfiniteQueryObserverBaseResult`](../interfaces/InfiniteQueryObserverBaseResult.md#properties). See the type above for what it changes. diff --git a/docs/framework/angular/reference/functions/injectIsFetching.md b/docs/framework/angular/reference/functions/injectIsFetching.md index ce629a0cf3f..c84d3c9b5ff 100644 --- a/docs/framework/angular/reference/functions/injectIsFetching.md +++ b/docs/framework/angular/reference/functions/injectIsFetching.md @@ -20,12 +20,33 @@ background (useful for app-wide loading indicators). The [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### options? [`InjectIsFetchingOptions`](../interfaces/InjectIsFetchingOptions.md) Additional configuration + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the isFetching signal. If this is not provided, the current injection context will be used instead (via `inject`). | + ## Returns `Signal`\<`number`\> diff --git a/docs/framework/angular/reference/functions/injectIsMutating.md b/docs/framework/angular/reference/functions/injectIsMutating.md index 665038e25dd..9a6e6798f93 100644 --- a/docs/framework/angular/reference/functions/injectIsMutating.md +++ b/docs/framework/angular/reference/functions/injectIsMutating.md @@ -20,12 +20,31 @@ Injects a signal that tracks the number of mutations that your application curre The [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### options? [`InjectIsMutatingOptions`](../interfaces/InjectIsMutatingOptions.md) Additional configuration + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the isMutating signal. If this is not provided, the current injection context will be used instead (via `inject`). | + ## Returns `Signal`\<`number`\> diff --git a/docs/framework/angular/reference/functions/injectMutation.md b/docs/framework/angular/reference/functions/injectMutation.md index 6af11f4fa48..f1c521966fc 100644 --- a/docs/framework/angular/reference/functions/injectMutation.md +++ b/docs/framework/angular/reference/functions/injectMutation.md @@ -39,12 +39,40 @@ Unlike queries, mutations are typically used to create/update/delete data or per A function that returns mutation options. Similar to `computed` from Angular, this function runs in the reactive context, so signals read inside it drive the mutation's options. + + +#### `injectMutationFn` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ### options? [`InjectMutationOptions`](../interfaces/InjectMutationOptions.md) Additional configuration + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the mutation. If this is not provided, the current injection context will be used instead (via `inject`). | + ## Returns [`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> diff --git a/docs/framework/angular/reference/functions/injectMutationState.md b/docs/framework/angular/reference/functions/injectMutationState.md index 450eccaa154..67174e5e68b 100644 --- a/docs/framework/angular/reference/functions/injectMutationState.md +++ b/docs/framework/angular/reference/functions/injectMutationState.md @@ -34,6 +34,14 @@ in the reactive context, so signals read inside it re-narrow the matched mutatio Additional configuration + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the mutation state signal. If this is not provided, the current injection context will be used instead (via `inject`). | + ## Returns `Signal`\<`TResult`[]\> diff --git a/docs/framework/angular/reference/functions/injectQuery.md b/docs/framework/angular/reference/functions/injectQuery.md index d4c64df0376..9a558fce7a2 100644 --- a/docs/framework/angular/reference/functions/injectQuery.md +++ b/docs/framework/angular/reference/functions/injectQuery.md @@ -3,6 +3,22 @@ id: injectQuery title: injectQuery --- +## Overview + +```ts +function injectQuery(injectQueryFn: () => DefinedInitialDataOptions, options?: InjectQueryOptions): DefinedCreateQueryResult; +function injectQuery(injectQueryFn: () => UndefinedInitialDataOptions, options?: InjectQueryOptions): CreateQueryResult; +function injectQuery(injectQueryFn: () => CreateQueryOptions, options?: InjectQueryOptions): CreateQueryResult; +``` + +- [`DefinedInitialDataOptions` → `DefinedCreateQueryResult`](#call-signature-1): This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`). +- [`UndefinedInitialDataOptions` → `CreateQueryResult`](#call-signature-2): Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. +- [`CreateQueryOptions` → `CreateQueryResult`](#call-signature-3): This overload accepts the general [CreateQueryOptions](../interfaces/CreateQueryOptions.md) shape rather than the `initialData`-aware overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping `injectQuery` in your own helper function that forwards caller-provided options. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -88,6 +104,8 @@ export class Posts { } ``` + + ## Call Signature ```ts @@ -206,6 +224,8 @@ export class Posts { } ``` + + ## Call Signature ```ts @@ -261,3 +281,70 @@ The query result. ### See https://tanstack.com/query/latest/docs/framework/angular/guides/queries + + + +## Parameters + +### injectQueryFn + +() => [`CreateQueryOptions`](../interfaces/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +A function that returns query options. Similar to `computed` from Angular, this +function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive +the query. + + + +#### `injectQueryFn` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryFnData` \| () => `TQueryFnData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| `NonFunctionGuard`\<`TQueryFnData`\> \| (`previousData`: `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryFnData`\>, `TError`, `NonFunctionGuard`\<`TQueryFnData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### options? + +[`InjectQueryOptions`](../interfaces/InjectQueryOptions.md) + +Additional configuration + + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `injector?` | `Injector` | The `Injector` in which to create the query. If this is not provided, the current injection context will be used instead (via `inject`). | + + + +## Returns + +[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\> + +The query result. diff --git a/docs/framework/angular/reference/functions/matchMutation.md b/docs/framework/angular/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/angular/reference/functions/matchMutation.md +++ b/docs/framework/angular/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/angular/reference/functions/matchQuery.md b/docs/framework/angular/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/angular/reference/functions/matchQuery.md +++ b/docs/framework/angular/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/angular/reference/functions/mutationOptions.md b/docs/framework/angular/reference/functions/mutationOptions.md index a68edb0aab2..8cefaa926a2 100644 --- a/docs/framework/angular/reference/functions/mutationOptions.md +++ b/docs/framework/angular/reference/functions/mutationOptions.md @@ -3,6 +3,20 @@ id: mutationOptions title: mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with `injectMutationState`. +- [`Omit` → `Omit`](#call-signature-2): You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No `mutationKey` is required on this overload — use this when you don't need to target the mutation via a `mutationKey` filter later (e.g. with `injectMutationState`); it can still be observed through other filters, such as `status`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -79,6 +93,8 @@ export class SavingIndicator { } ``` + + ## Call Signature ```ts @@ -165,3 +181,34 @@ export class Post { } } ``` + + + +## Parameters + +### options + +`Omit`\<[`CreateMutationOptions`](../interfaces/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The mutation options to use, identical to what you'd pass to `injectMutation`, without a +`mutationKey`. + + + +#### `options` properties + +Built from [`CreateMutationOptions`](../interfaces/CreateMutationOptions.md#properties). See the type above for what it changes. + + + +## Returns + +`Omit`\<[`CreateMutationOptions`](../interfaces/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + + + +### Result properties + +Built from [`CreateMutationOptions`](../interfaces/CreateMutationOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/angular/reference/functions/noop.md b/docs/framework/angular/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/angular/reference/functions/noop.md +++ b/docs/framework/angular/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/angular/reference/functions/queryFeature.md b/docs/framework/angular/reference/functions/queryFeature.md index ac98f4c34f9..ea8a90c9aae 100644 --- a/docs/framework/angular/reference/functions/queryFeature.md +++ b/docs/framework/angular/reference/functions/queryFeature.md @@ -36,3 +36,12 @@ The Angular providers this feature contributes to `provideTanStackQuery`. [`QueryFeature`](../interfaces/QueryFeature.md)\<`TFeatureKind`\> A Query feature. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `ɵkind` | `TFeatureKind` | The kind of the feature, e.g. `'Devtools'` or `'PersistQueryClient'`. | +| `ɵproviders` | `Provider`[] | The providers that `provideTanStackQuery` registers for the feature. | diff --git a/docs/framework/angular/reference/functions/queryOptions.md b/docs/framework/angular/reference/functions/queryOptions.md index 4f8fc331648..3b7fbe80fbf 100644 --- a/docs/framework/angular/reference/functions/queryOptions.md +++ b/docs/framework/angular/reference/functions/queryOptions.md @@ -3,6 +3,22 @@ id: queryOptions title: queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialDataOptions): Omit, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UnusedSkipTokenOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UndefinedInitialDataOptions): CreateQueryOptions & object & QueryKeyWithDataTag; +``` + +- [`DefinedInitialDataOptions` → `Omit`](#call-signature-1): You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is required and is the query key to generate options for. +- [`UnusedSkipTokenOptions` → `OmitKeyof`](#call-signature-2): You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is required and is the query key to generate options for. +- [`UndefinedInitialDataOptions` → `CreateQueryOptions`](#call-signature-3): You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is required and is the query key to generate options for. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -85,6 +101,8 @@ export class Posts { } ``` + + ## Call Signature ```ts @@ -162,6 +180,8 @@ export class Post { } ``` + + ## Call Signature ```ts @@ -272,3 +292,25 @@ export class Post { readonly postQuery = injectQuery(() => postOptions(this.postId())) } ``` + + + +## Parameters + +### options + +[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `injectQuery`. + + + +#### `options` properties + +Built from [`CreateQueryOptions`](../interfaces/CreateQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/lit/reference/functions/createInfiniteQueryController.md b/docs/framework/lit/reference/functions/createInfiniteQueryController.md index c885e2ee44a..4231dfd07b9 100644 --- a/docs/framework/lit/reference/functions/createInfiniteQueryController.md +++ b/docs/framework/lit/reference/functions/createInfiniteQueryController.md @@ -61,6 +61,43 @@ subscription. Infinite query observer options, or a getter that returns options. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/createMutationController.md b/docs/framework/lit/reference/functions/createMutationController.md index 23f9c7c23b3..78ad304640c 100644 --- a/docs/framework/lit/reference/functions/createMutationController.md +++ b/docs/framework/lit/reference/functions/createMutationController.md @@ -55,6 +55,26 @@ subscription. Mutation observer options, or a getter that returns options. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/createQueriesController.md b/docs/framework/lit/reference/functions/createQueriesController.md index 091e44f0a37..b43f0043b2e 100644 --- a/docs/framework/lit/reference/functions/createQueriesController.md +++ b/docs/framework/lit/reference/functions/createQueriesController.md @@ -47,6 +47,15 @@ subscription. Queries controller options, or a getter that returns options. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `combine?` | (`result`: `CreateQueriesResults`\<`TQueryOptions`\>) => `TCombinedResult` | Optional function that combines the query result array into one value. | +| `queries` | [`Accessor`](../type-aliases/Accessor.md)\< \| readonly \[`...CreateQueriesOptions`\] \| readonly \[`...{ [K in keyof TQueryOptions]: GetCreateQueriesInput }`\]\> | Query options to observe, or a getter that returns the current options. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/createQueryController.md b/docs/framework/lit/reference/functions/createQueryController.md index 947bd70647c..d011c0ff658 100644 --- a/docs/framework/lit/reference/functions/createQueryController.md +++ b/docs/framework/lit/reference/functions/createQueryController.md @@ -58,6 +58,40 @@ subscription. Query observer options, or a getter that returns options. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryData` \| () => `TQueryData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| `NonFunctionGuard`\<`TQueryData`\> \| (`previousData`: `NonFunctionGuard`\<`TQueryData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryData`\>, `TError`, `NonFunctionGuard`\<`TQueryData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryData`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/dehydrate.md b/docs/framework/lit/reference/functions/dehydrate.md index 53b1fc5eba7..e01b3cf74ef 100644 --- a/docs/framework/lit/reference/functions/dehydrate.md +++ b/docs/framework/lit/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/lit/reference/functions/hydrate.md b/docs/framework/lit/reference/functions/hydrate.md index 26ce5c10fed..9772d216cee 100644 --- a/docs/framework/lit/reference/functions/hydrate.md +++ b/docs/framework/lit/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/lit/reference/functions/infiniteQueryOptions.md b/docs/framework/lit/reference/functions/infiniteQueryOptions.md index 90a37c312d4..25fe68159e1 100644 --- a/docs/framework/lit/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/lit/reference/functions/infiniteQueryOptions.md @@ -42,12 +42,55 @@ data and error types across TanStack Query APIs. Infinite query options to preserve and brand. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + ## Returns [`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` The same options object with a typed `queryKey`. + + +### Result properties + +Built from [`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md#properties). See the type above for what it changes. + ## Example ```ts diff --git a/docs/framework/lit/reference/functions/matchMutation.md b/docs/framework/lit/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/lit/reference/functions/matchMutation.md +++ b/docs/framework/lit/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/lit/reference/functions/matchQuery.md b/docs/framework/lit/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/lit/reference/functions/matchQuery.md +++ b/docs/framework/lit/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/lit/reference/functions/mutationOptions.md b/docs/framework/lit/reference/functions/mutationOptions.md index e396dcd5837..a14d99eecc3 100644 --- a/docs/framework/lit/reference/functions/mutationOptions.md +++ b/docs/framework/lit/reference/functions/mutationOptions.md @@ -37,12 +37,52 @@ Preserves and types mutation options for reuse across Lit Query APIs. Mutation options to preserve. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ## Returns [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> The same options object. + + +### Result properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ## Example ```ts diff --git a/docs/framework/lit/reference/functions/noop.md b/docs/framework/lit/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/lit/reference/functions/noop.md +++ b/docs/framework/lit/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/lit/reference/functions/queryOptions.md b/docs/framework/lit/reference/functions/queryOptions.md index a76aa3e3478..33766a7f5ad 100644 --- a/docs/framework/lit/reference/functions/queryOptions.md +++ b/docs/framework/lit/reference/functions/queryOptions.md @@ -3,6 +3,22 @@ id: queryOptions title: queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialDataOptions): Omit, "queryFn"> & object & object; +function queryOptions(options: UnusedSkipTokenOptions): OmitKeyof, "queryFn"> & object & object; +function queryOptions(options: UndefinedInitialDataOptions): QueryObserverOptions & object & object; +``` + +- [`DefinedInitialDataOptions` → `Omit`](#call-signature-1): Brands query options so the `queryKey` carries the query function data and error types across TanStack Query APIs. +- [`UnusedSkipTokenOptions` → `OmitKeyof`](#call-signature-2): Brands query options so the `queryKey` carries the query function data and error types across TanStack Query APIs. +- [`UndefinedInitialDataOptions` → `QueryObserverOptions`](#call-signature-3): Brands query options so the `queryKey` carries the query function data and error types across TanStack Query APIs. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -58,6 +74,8 @@ const todosOptions = queryOptions({ }) ``` + + ## Call Signature ```ts @@ -101,6 +119,8 @@ Query options to preserve and brand. The same options object with a typed `queryKey`. + + ## Call Signature ```ts @@ -143,3 +163,33 @@ Query options to preserve and brand. [`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`, `never`\> & `object` & `object` The same options object with a typed `queryKey`. + + + +## Parameters + +### options + +[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +Query options to preserve and brand. + + + +#### `options` properties + +Built from [`QueryObserverOptions`](../interfaces/QueryObserverOptions.md#properties). See the type above for what it changes. + + + +## Returns + +[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`, `never`\> & `object` & `object` + +The same options object with a typed `queryKey`. + + + +### Result properties + +Built from [`QueryObserverOptions`](../interfaces/QueryObserverOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/lit/reference/functions/useIsFetching.md b/docs/framework/lit/reference/functions/useIsFetching.md index 23f14072621..79ed9a3e367 100644 --- a/docs/framework/lit/reference/functions/useIsFetching.md +++ b/docs/framework/lit/reference/functions/useIsFetching.md @@ -34,6 +34,19 @@ subscription. Query filters, or a getter that returns query filters. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/useIsMutating.md b/docs/framework/lit/reference/functions/useIsMutating.md index 7c01a56f935..77ffe170fe1 100644 --- a/docs/framework/lit/reference/functions/useIsMutating.md +++ b/docs/framework/lit/reference/functions/useIsMutating.md @@ -34,6 +34,17 @@ subscription. Mutation filters, or a getter that returns mutation filters. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/lit/reference/functions/useMutationState.md b/docs/framework/lit/reference/functions/useMutationState.md index 9a21573d756..ede6d8cb9e2 100644 --- a/docs/framework/lit/reference/functions/useMutationState.md +++ b/docs/framework/lit/reference/functions/useMutationState.md @@ -41,6 +41,15 @@ subscription. Mutation state filters and optional selector. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `filters?` | [`Accessor`](../type-aliases/Accessor.md)\<[`MutationFilters`](../interfaces/MutationFilters.md)\> | Filters used to select mutations from the mutation cache. | +| `select?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `TResult` | Maps each matching mutation to the value returned by the accessor. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/preact/reference/functions/HydrationBoundary.md b/docs/framework/preact/reference/functions/HydrationBoundary.md index 07db96102fd..4de7af659ad 100644 --- a/docs/framework/preact/reference/functions/HydrationBoundary.md +++ b/docs/framework/preact/reference/functions/HydrationBoundary.md @@ -24,6 +24,17 @@ Note: Only `queries` can be dehydrated with an `HydrationBoundary`. The dehydrated `state` to hydrate, the hydrate `options`, an optional custom `queryClient`, and the `children` to render. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children?` | `ComponentChildren` | 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?` | [`OmitKeyof`](../type-aliases/OmitKeyof.md)\<[`HydrateOptions`](../interfaces/HydrateOptions.md), `"defaultOptions"`\> & `object` | Optional. Note: unlike `hydrate`, `mutations` cannot be set here. | +| `queryClient?` | [`QueryClient`](../classes/QueryClient.md) | Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. | +| `state` | [`DehydratedState`](../interfaces/DehydratedState.md) \| `null` \| `undefined` | The state to hydrate. | + ## Returns `Element` diff --git a/docs/framework/preact/reference/functions/QueryClientProvider.md b/docs/framework/preact/reference/functions/QueryClientProvider.md index 95fa73be1f9..eb0f56ff2fd 100644 --- a/docs/framework/preact/reference/functions/QueryClientProvider.md +++ b/docs/framework/preact/reference/functions/QueryClientProvider.md @@ -22,6 +22,15 @@ comes back online). The `client` to provide, and the `children` that get access to it. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children?` | `ComponentChildren` | The components that get access to the provided `QueryClient`. | +| `client` | [`QueryClient`](../classes/QueryClient.md) | **Required** The `QueryClient` instance to provide. | + ## Returns `VNode` diff --git a/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md b/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md index 5cac302da98..6531ae5d962 100644 --- a/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md +++ b/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md @@ -21,6 +21,14 @@ reset any query errors within the boundaries of the component. The `children` to render. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children` | \| `ComponentChildren` \| [`QueryErrorResetBoundaryFunction`](../type-aliases/QueryErrorResetBoundaryFunction.md) | Either a plain node, or a function that receives the boundary's QueryErrorResetBoundaryValue and returns a node. | + ## Returns `Element` diff --git a/docs/framework/preact/reference/functions/dehydrate.md b/docs/framework/preact/reference/functions/dehydrate.md index 53b1fc5eba7..e01b3cf74ef 100644 --- a/docs/framework/preact/reference/functions/dehydrate.md +++ b/docs/framework/preact/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/preact/reference/functions/hydrate.md b/docs/framework/preact/reference/functions/hydrate.md index 5e250b9da2b..e160e90a332 100644 --- a/docs/framework/preact/reference/functions/hydrate.md +++ b/docs/framework/preact/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/preact/reference/functions/infiniteQueryOptions.md b/docs/framework/preact/reference/functions/infiniteQueryOptions.md index 1c59af27af3..d52d022d642 100644 --- a/docs/framework/preact/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/preact/reference/functions/infiniteQueryOptions.md @@ -3,6 +3,22 @@ id: infiniteQueryOptions title: infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: DefinedInitialDataInfiniteOptions): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UnusedSkipTokenInfiniteOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UndefinedInitialDataInfiniteOptions): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +- [`DefinedInitialDataInfiniteOptions` → `UseInfiniteQueryOptions`](#call-signature-1): 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. +- [`UnusedSkipTokenInfiniteOptions` → `OmitKeyof`](#call-signature-2): 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. +- [`UndefinedInitialDataInfiniteOptions` → `UseInfiniteQueryOptions`](#call-signature-3): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -89,6 +105,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -172,6 +190,8 @@ function Comments({ postId }: { postId: string }) { } ``` + + ## Call Signature ```ts @@ -254,3 +274,25 @@ function Comments({ postId }: { postId: string }) { ) } ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/preact/reference/functions/matchMutation.md b/docs/framework/preact/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/preact/reference/functions/matchMutation.md +++ b/docs/framework/preact/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/preact/reference/functions/matchQuery.md b/docs/framework/preact/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/preact/reference/functions/matchQuery.md +++ b/docs/framework/preact/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/preact/reference/functions/mutationOptions.md b/docs/framework/preact/reference/functions/mutationOptions.md index 5417f6370ef..879cacb7547 100644 --- a/docs/framework/preact/reference/functions/mutationOptions.md +++ b/docs/framework/preact/reference/functions/mutationOptions.md @@ -3,6 +3,20 @@ id: mutationOptions title: mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): 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`. +- [`Omit` → `Omit`](#call-signature-2): 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 target the mutation via a `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, such as `status`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -72,6 +86,8 @@ function SavingIndicator() { } ``` + + ## Call Signature ```ts @@ -140,3 +156,34 @@ function CreatePost() { return } ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseMutationOptions`](../interfaces/UseMutationOptions.md#properties). See the type above for what it changes. + + + +## Returns + +`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + + + +### Result properties + +Built from [`UseMutationOptions`](../interfaces/UseMutationOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/preact/reference/functions/noop.md b/docs/framework/preact/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/preact/reference/functions/noop.md +++ b/docs/framework/preact/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/preact/reference/functions/queryOptions.md b/docs/framework/preact/reference/functions/queryOptions.md index a33462344e7..5614deb0347 100644 --- a/docs/framework/preact/reference/functions/queryOptions.md +++ b/docs/framework/preact/reference/functions/queryOptions.md @@ -3,6 +3,22 @@ id: queryOptions title: queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialDataOptions): Omit, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UnusedSkipTokenOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UndefinedInitialDataOptions): UseQueryOptions & object & QueryKeyWithDataTag; +``` + +- [`DefinedInitialDataOptions` → `Omit`](#call-signature-1): 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. +- [`UnusedSkipTokenOptions` → `OmitKeyof`](#call-signature-2): 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. +- [`UndefinedInitialDataOptions` → `UseQueryOptions`](#call-signature-3): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -80,6 +96,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -149,6 +167,8 @@ function Post({ id }: { id: string }) { } ``` + + ## Call Signature ```ts @@ -242,3 +262,25 @@ function Post({ postId }: { postId: number | undefined }) { return

{data?.title}

} ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseQueryOptions`](../interfaces/UseQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/preact/reference/functions/useInfiniteQuery.md b/docs/framework/preact/reference/functions/useInfiniteQuery.md index e44e8b71ca2..7977db6f0ec 100644 --- a/docs/framework/preact/reference/functions/useInfiniteQuery.md +++ b/docs/framework/preact/reference/functions/useInfiniteQuery.md @@ -3,6 +3,22 @@ id: useInfiniteQuery title: useInfiniteQuery --- +## Overview + +```ts +function useInfiniteQuery(options: DefinedInitialDataInfiniteOptions, queryClient?: QueryClient): DefinedUseInfiniteQueryResult; +function useInfiniteQuery(options: UndefinedInitialDataInfiniteOptions, queryClient?: QueryClient): UseInfiniteQueryResult; +function useInfiniteQuery(options: UseInfiniteQueryOptions, queryClient?: QueryClient): UseInfiniteQueryResult; +``` + +- [`DefinedInitialDataInfiniteOptions` → `DefinedUseInfiniteQueryResult`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UndefinedInitialDataInfiniteOptions` → `UseInfiniteQueryResult`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UseInfiniteQueryOptions` → `UseInfiniteQueryResult`](#call-signature-3): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -99,6 +115,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -259,6 +277,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -447,3 +467,108 @@ function Comments({ postId }: { postId: string | undefined }) { ) } ``` + + + +## Parameters + +### options + +[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use — everything you can pass to `useInfiniteQuery`. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +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 `fetchNextPage`, `fetchPreviousPage`, +`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and +`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default +`InfiniteData` shape. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. | +| `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `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). | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. | +| `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. | +| `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. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/preact/reference/functions/useIsFetching.md b/docs/framework/preact/reference/functions/useIsFetching.md index a1fb0e9b0cb..e690fb5bf05 100644 --- a/docs/framework/preact/reference/functions/useIsFetching.md +++ b/docs/framework/preact/reference/functions/useIsFetching.md @@ -20,6 +20,19 @@ the background (useful for app-wide loading indicators). The [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/preact/reference/functions/useIsMutating.md b/docs/framework/preact/reference/functions/useIsMutating.md index 0bec0868b1b..b18e138abf9 100644 --- a/docs/framework/preact/reference/functions/useIsMutating.md +++ b/docs/framework/preact/reference/functions/useIsMutating.md @@ -20,6 +20,17 @@ The `useIsMutating` hook returns the `number` of mutations that your application The [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/preact/reference/functions/useMutation.md b/docs/framework/preact/reference/functions/useMutation.md index 43b9bbfc093..2fb4df9d71b 100644 --- a/docs/framework/preact/reference/functions/useMutation.md +++ b/docs/framework/preact/reference/functions/useMutation.md @@ -38,6 +38,26 @@ Unlike queries, mutations are typically used to create/update/delete data or per The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use — everything you can pass to `useMutation`. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -55,6 +75,12 @@ mutation definition. Hook-level callbacks (passed to `options`) fire for every m 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. + + +### Result properties + +Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes. + ## Throws The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is diff --git a/docs/framework/preact/reference/functions/usePrefetchQuery.md b/docs/framework/preact/reference/functions/usePrefetchQuery.md index d43b254e805..74b28817410 100644 --- a/docs/framework/preact/reference/functions/usePrefetchQuery.md +++ b/docs/framework/preact/reference/functions/usePrefetchQuery.md @@ -48,6 +48,12 @@ already there or already in flight. The [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`. + + +#### `options` properties + +Built from [`QueryExecuteOptions`](../interfaces/QueryExecuteOptions.md#properties). See the type above for what it changes. + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/preact/reference/functions/useQuery.md b/docs/framework/preact/reference/functions/useQuery.md index 766aa4746cf..5635ee7c5a4 100644 --- a/docs/framework/preact/reference/functions/useQuery.md +++ b/docs/framework/preact/reference/functions/useQuery.md @@ -3,6 +3,22 @@ id: useQuery title: useQuery --- +## Overview + +```ts +function useQuery(options: DefinedInitialDataOptions, queryClient?: QueryClient): DefinedUseQueryResult; +function useQuery(options: UndefinedInitialDataOptions, queryClient?: QueryClient): UseQueryResult; +function useQuery(options: UseQueryOptions, queryClient?: QueryClient): UseQueryResult; +``` + +- [`DefinedInitialDataOptions` → `DefinedUseQueryResult`](#call-signature-1): This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). +- [`UndefinedInitialDataOptions` → `UseQueryResult`](#call-signature-2): This overload is selected when `initialData` is omitted or may be `undefined`, so the resulting `data` can be `undefined`. +- [`UseQueryOptions` → `UseQueryResult`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known — for example, an object typed as [UseQueryOptions](../interfaces/UseQueryOptions.md) rather than an object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -84,6 +100,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -188,6 +206,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -389,3 +409,96 @@ function Posts() { ) } ``` + + + +## Parameters + +### options + +[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use — everything you can pass to `useQuery`. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryFnData` \| () => `TQueryFnData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| `NonFunctionGuard`\<`TQueryFnData`\> \| (`previousData`: `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryFnData`\>, `TError`, `NonFunctionGuard`\<`TQueryFnData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +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. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md b/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md index e2e73b5aa9c..01a165c6d4e 100644 --- a/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md +++ b/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md @@ -44,6 +44,40 @@ Caveat: cancellation does not work. The [UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) to use — the same options as `useInfiniteQuery`, minus the ones listed above. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `queryFn?` | (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | `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. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -59,6 +93,12 @@ The same object as `useInfiniteQuery`, except that `data` is guaranteed to be de `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + + +### Result properties + +Built from [`InfiniteQueryObserverBaseResult`](../interfaces/InfiniteQueryObserverBaseResult.md#properties). See the type above for what it changes. + ## Remarks Multiple suspenseful query calls in the same component suspend serially, causing a request diff --git a/docs/framework/preact/reference/functions/useSuspenseQueries.md b/docs/framework/preact/reference/functions/useSuspenseQueries.md index 3ce249c777c..fd3596a4181 100644 --- a/docs/framework/preact/reference/functions/useSuspenseQueries.md +++ b/docs/framework/preact/reference/functions/useSuspenseQueries.md @@ -3,6 +3,20 @@ id: useSuspenseQueries title: useSuspenseQueries --- +## Overview + +```ts +function useSuspenseQueries(options: object, queryClient?: QueryClient): TCombinedResult; +function useSuspenseQueries(options: object, queryClient?: QueryClient): TCombinedResult; +``` + +- [`object` → `TCombinedResult`](#call-signature-1): 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`. +- [`object` → `TCombinedResult`](#call-signature-2): 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`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -273,6 +287,8 @@ function ErrorBoundary({ } ``` + + ## Call Signature ```ts @@ -476,3 +492,45 @@ function ErrorBoundary({ return children } ``` + + + +## Parameters + +### options + +The `queries` array to run in Suspense, and an optional `combine` function. + +#### combine? + +(`result`: `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \}) => `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`](../classes/QueryClient.md) + +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. diff --git a/docs/framework/preact/reference/functions/useSuspenseQuery.md b/docs/framework/preact/reference/functions/useSuspenseQuery.md index 1bbde5be436..c75c49333f4 100644 --- a/docs/framework/preact/reference/functions/useSuspenseQuery.md +++ b/docs/framework/preact/reference/functions/useSuspenseQuery.md @@ -40,6 +40,37 @@ Caveat: cancellation does not work. The [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) to use — the same options as `useQuery`, minus the ones listed above. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryFnData` \| () => `TQueryFnData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `queryFn?` | (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | `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. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -54,6 +85,12 @@ be used. 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). + + +### Result properties + +Built from [`QueryObserverBaseResult`](../interfaces/QueryObserverBaseResult.md#properties). See the type above for what it changes. + ## Remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request diff --git a/docs/framework/react/reference/functions/HydrationBoundary.md b/docs/framework/react/reference/functions/HydrationBoundary.md index ec422747f17..d34306f72db 100644 --- a/docs/framework/react/reference/functions/HydrationBoundary.md +++ b/docs/framework/react/reference/functions/HydrationBoundary.md @@ -24,6 +24,17 @@ Note: Only `queries` can be dehydrated with an `HydrationBoundary`. The dehydrated `state` to hydrate, the hydrate `options`, an optional custom `queryClient`, and the `children` to render. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children?` | `ReactNode` | 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?` | [`OmitKeyof`](../type-aliases/OmitKeyof.md)\<[`HydrateOptions`](../interfaces/HydrateOptions.md), `"defaultOptions"`\> & `object` | Optional. Note: unlike `hydrate`, `mutations` cannot be set here. | +| `queryClient?` | [`QueryClient`](../classes/QueryClient.md) | Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. | +| `state` | [`DehydratedState`](../interfaces/DehydratedState.md) \| `null` \| `undefined` | The state to hydrate. | + ## Returns `ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> diff --git a/docs/framework/react/reference/functions/QueryClientProvider.md b/docs/framework/react/reference/functions/QueryClientProvider.md index ea0a4c39574..5b0778b6b1c 100644 --- a/docs/framework/react/reference/functions/QueryClientProvider.md +++ b/docs/framework/react/reference/functions/QueryClientProvider.md @@ -24,6 +24,15 @@ comes back online). The `client` to provide, and the `children` that get access to it. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children?` | `React.ReactNode` | The components that get access to the provided `QueryClient`. | +| `client` | [`QueryClient`](../classes/QueryClient.md) | **Required** The `QueryClient` instance to provide. | + ## Returns `Element` diff --git a/docs/framework/react/reference/functions/QueryErrorResetBoundary.md b/docs/framework/react/reference/functions/QueryErrorResetBoundary.md index 0365df4f43b..1283aeba32e 100644 --- a/docs/framework/react/reference/functions/QueryErrorResetBoundary.md +++ b/docs/framework/react/reference/functions/QueryErrorResetBoundary.md @@ -23,6 +23,14 @@ reset any query errors within the boundaries of the component. The `children` to render. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children` | \| `ReactNode` \| [`QueryErrorResetBoundaryFunction`](../type-aliases/QueryErrorResetBoundaryFunction.md) | Either a plain node, or a function that receives the boundary's QueryErrorResetBoundaryValue and returns a node. | + ## Returns `Element` diff --git a/docs/framework/react/reference/functions/dehydrate.md b/docs/framework/react/reference/functions/dehydrate.md index 53b1fc5eba7..e01b3cf74ef 100644 --- a/docs/framework/react/reference/functions/dehydrate.md +++ b/docs/framework/react/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/react/reference/functions/hydrate.md b/docs/framework/react/reference/functions/hydrate.md index 5e250b9da2b..e160e90a332 100644 --- a/docs/framework/react/reference/functions/hydrate.md +++ b/docs/framework/react/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/react/reference/functions/infiniteQueryOptions.md b/docs/framework/react/reference/functions/infiniteQueryOptions.md index 78bec4e0eca..4fe2117edfc 100644 --- a/docs/framework/react/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/react/reference/functions/infiniteQueryOptions.md @@ -5,6 +5,22 @@ redirect_from: - framework/react/reference/infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: DefinedInitialDataInfiniteOptions): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UnusedSkipTokenInfiniteOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UndefinedInitialDataInfiniteOptions): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +- [`DefinedInitialDataInfiniteOptions` → `UseInfiniteQueryOptions`](#call-signature-1): 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. +- [`UnusedSkipTokenInfiniteOptions` → `OmitKeyof`](#call-signature-2): 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. +- [`UndefinedInitialDataInfiniteOptions` → `UseInfiniteQueryOptions`](#call-signature-3): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -91,6 +107,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -174,6 +192,8 @@ function Comments({ postId }: { postId: string }) { } ``` + + ## Call Signature ```ts @@ -256,3 +276,25 @@ function Comments({ postId }: { postId: string }) { ) } ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/react/reference/functions/matchMutation.md b/docs/framework/react/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/react/reference/functions/matchMutation.md +++ b/docs/framework/react/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/react/reference/functions/matchQuery.md b/docs/framework/react/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/react/reference/functions/matchQuery.md +++ b/docs/framework/react/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/react/reference/functions/mutationOptions.md b/docs/framework/react/reference/functions/mutationOptions.md index dd17126af7e..431b3b78c5a 100644 --- a/docs/framework/react/reference/functions/mutationOptions.md +++ b/docs/framework/react/reference/functions/mutationOptions.md @@ -5,6 +5,20 @@ redirect_from: - framework/react/reference/mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): 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`. +- [`Omit` → `Omit`](#call-signature-2): 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 target the mutation via a `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, such as `status`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -74,6 +88,8 @@ function SavingIndicator() { } ``` + + ## Call Signature ```ts @@ -142,3 +158,34 @@ function CreatePost() { return } ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseMutationOptions`](../interfaces/UseMutationOptions.md#properties). See the type above for what it changes. + + + +## Returns + +`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + + + +### Result properties + +Built from [`UseMutationOptions`](../interfaces/UseMutationOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/react/reference/functions/noop.md b/docs/framework/react/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/react/reference/functions/noop.md +++ b/docs/framework/react/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/react/reference/functions/queryOptions.md b/docs/framework/react/reference/functions/queryOptions.md index ccc6e8806e9..f6982db9d38 100644 --- a/docs/framework/react/reference/functions/queryOptions.md +++ b/docs/framework/react/reference/functions/queryOptions.md @@ -5,6 +5,22 @@ redirect_from: - framework/react/reference/queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialDataOptions): Omit, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UnusedSkipTokenOptions): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag; +function queryOptions(options: UndefinedInitialDataOptions): UseQueryOptions & object & QueryKeyWithDataTag; +``` + +- [`DefinedInitialDataOptions` → `Omit`](#call-signature-1): 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. +- [`UnusedSkipTokenOptions` → `OmitKeyof`](#call-signature-2): 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. +- [`UndefinedInitialDataOptions` → `UseQueryOptions`](#call-signature-3): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -82,6 +98,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -151,6 +169,8 @@ function Post({ id }: { id: string }) { } ``` + + ## Call Signature ```ts @@ -244,3 +264,25 @@ function Post({ postId }: { postId: number | undefined }) { return

{data?.title}

} ``` + + + +## 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`. + + + +#### `options` properties + +Built from [`UseQueryOptions`](../interfaces/UseQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/react/reference/functions/useInfiniteQuery.md b/docs/framework/react/reference/functions/useInfiniteQuery.md index 92898d56628..a82947d929d 100644 --- a/docs/framework/react/reference/functions/useInfiniteQuery.md +++ b/docs/framework/react/reference/functions/useInfiniteQuery.md @@ -5,6 +5,22 @@ redirect_from: - framework/react/reference/useInfiniteQuery --- +## Overview + +```ts +function useInfiniteQuery(options: DefinedInitialDataInfiniteOptions, queryClient?: QueryClient): DefinedUseInfiniteQueryResult; +function useInfiniteQuery(options: UndefinedInitialDataInfiniteOptions, queryClient?: QueryClient): UseInfiniteQueryResult; +function useInfiniteQuery(options: UseInfiniteQueryOptions, queryClient?: QueryClient): UseInfiniteQueryResult; +``` + +- [`DefinedInitialDataInfiniteOptions` → `DefinedUseInfiniteQueryResult`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UndefinedInitialDataInfiniteOptions` → `UseInfiniteQueryResult`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UseInfiniteQueryOptions` → `UseInfiniteQueryResult`](#call-signature-3): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -101,6 +117,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -261,6 +279,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -449,3 +469,108 @@ function Comments({ postId }: { postId: string | undefined }) { ) } ``` + + + +## Parameters + +### options + +[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use — everything you can pass to `useInfiniteQuery`. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +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 `fetchNextPage`, `fetchPreviousPage`, +`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and +`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default +`InfiniteData` shape. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. | +| `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `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). | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. | +| `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. | +| `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. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/react/reference/functions/useIsFetching.md b/docs/framework/react/reference/functions/useIsFetching.md index 14ff6df65e4..c6687b91131 100644 --- a/docs/framework/react/reference/functions/useIsFetching.md +++ b/docs/framework/react/reference/functions/useIsFetching.md @@ -22,6 +22,19 @@ the background (useful for app-wide loading indicators). The [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/react/reference/functions/useIsMutating.md b/docs/framework/react/reference/functions/useIsMutating.md index 25f2c8891f8..8b1a40fbe5b 100644 --- a/docs/framework/react/reference/functions/useIsMutating.md +++ b/docs/framework/react/reference/functions/useIsMutating.md @@ -22,6 +22,17 @@ The `useIsMutating` hook returns the `number` of mutations that your application The [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/react/reference/functions/useMutation.md b/docs/framework/react/reference/functions/useMutation.md index 29955dbd050..db22ad35136 100644 --- a/docs/framework/react/reference/functions/useMutation.md +++ b/docs/framework/react/reference/functions/useMutation.md @@ -40,6 +40,26 @@ Unlike queries, mutations are typically used to create/update/delete data or per The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use — everything you can pass to `useMutation`. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. | +| `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. | +| `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. | +| `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. | +| `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. | +| `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. | +| `throwOnError?` | `boolean` \| (`error`: `TError`) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -57,6 +77,12 @@ mutation definition. Hook-level callbacks (passed to `options`) fire for every m 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. + + +### Result properties + +Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes. + ## Throws The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is diff --git a/docs/framework/react/reference/functions/usePrefetchQuery.md b/docs/framework/react/reference/functions/usePrefetchQuery.md index dfa752b8577..77fa2e03cfe 100644 --- a/docs/framework/react/reference/functions/usePrefetchQuery.md +++ b/docs/framework/react/reference/functions/usePrefetchQuery.md @@ -50,6 +50,12 @@ already there or already in flight. The [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`. + + +#### `options` properties + +Built from [`QueryExecuteOptions`](../interfaces/QueryExecuteOptions.md#properties). See the type above for what it changes. + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/react/reference/functions/useQuery.md b/docs/framework/react/reference/functions/useQuery.md index 9d9a3994fa0..a2fb1c7aa88 100644 --- a/docs/framework/react/reference/functions/useQuery.md +++ b/docs/framework/react/reference/functions/useQuery.md @@ -5,6 +5,22 @@ redirect_from: - framework/react/reference/useQuery --- +## Overview + +```ts +function useQuery(options: DefinedInitialDataOptions, queryClient?: QueryClient): DefinedUseQueryResult; +function useQuery(options: UndefinedInitialDataOptions, queryClient?: QueryClient): UseQueryResult; +function useQuery(options: UseQueryOptions, queryClient?: QueryClient): UseQueryResult; +``` + +- [`DefinedInitialDataOptions` → `DefinedUseQueryResult`](#call-signature-1): This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). +- [`UndefinedInitialDataOptions` → `UseQueryResult`](#call-signature-2): This overload is selected when `initialData` is omitted or may be `undefined`, so the resulting `data` can be `undefined`. +- [`UseQueryOptions` → `UseQueryResult`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known — for example, an object typed as [UseQueryOptions](../interfaces/UseQueryOptions.md) rather than an object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -86,6 +102,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -190,6 +208,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -391,3 +411,96 @@ function Posts() { ) } ``` + + + +## Parameters + +### options + +[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use — everything you can pass to `useQuery`. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryFnData` \| () => `TQueryFnData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| `NonFunctionGuard`\<`TQueryFnData`\> \| (`previousData`: `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryFnData`\>, `TError`, `NonFunctionGuard`\<`TQueryFnData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryFnData`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +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. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md b/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md index b655ce35f5d..b0d76cd4e6f 100644 --- a/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md +++ b/docs/framework/react/reference/functions/useSuspenseInfiniteQuery.md @@ -46,6 +46,40 @@ Caveat: cancellation does not work. The [UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) to use — the same options as `useInfiniteQuery`, minus the ones listed above. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `queryFn?` | (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | `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. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -61,6 +95,12 @@ The same object as `useInfiniteQuery`, except that `data` is guaranteed to be de `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + + +### Result properties + +Built from [`InfiniteQueryObserverBaseResult`](../interfaces/InfiniteQueryObserverBaseResult.md#properties). See the type above for what it changes. + ## Remarks Multiple suspenseful query calls in the same component suspend serially, causing a request diff --git a/docs/framework/react/reference/functions/useSuspenseQueries.md b/docs/framework/react/reference/functions/useSuspenseQueries.md index cc627dd2cd2..7e0fe744311 100644 --- a/docs/framework/react/reference/functions/useSuspenseQueries.md +++ b/docs/framework/react/reference/functions/useSuspenseQueries.md @@ -5,6 +5,20 @@ redirect_from: - framework/react/reference/useSuspenseQueries --- +## Overview + +```ts +function useSuspenseQueries(options: object, queryClient?: QueryClient): TCombinedResult; +function useSuspenseQueries(options: object, queryClient?: QueryClient): TCombinedResult; +``` + +- [`object` → `TCombinedResult`](#call-signature-1): 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`. +- [`object` → `TCombinedResult`](#call-signature-2): 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`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -215,6 +229,8 @@ function App() { } ``` + + ## Call Signature ```ts @@ -378,3 +394,45 @@ function App() { ) } ``` + + + +## Parameters + +### options + +The `queries` array to run in Suspense, and an optional `combine` function. + +#### combine? + +(`result`: `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\\]\> \}) => `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`](../classes/QueryClient.md) + +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. diff --git a/docs/framework/react/reference/functions/useSuspenseQuery.md b/docs/framework/react/reference/functions/useSuspenseQuery.md index ad4f9421826..1dee6c13117 100644 --- a/docs/framework/react/reference/functions/useSuspenseQuery.md +++ b/docs/framework/react/reference/functions/useSuspenseQuery.md @@ -42,6 +42,37 @@ Caveat: cancellation does not work. The [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) to use — the same options as `useQuery`, minus the ones listed above. + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryFnData` \| () => `TQueryFnData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `queryFn?` | (`context`: `object`) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | `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. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryFnData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryFnData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `subscribed?` | `boolean` | `true` | Set this to `false` to unsubscribe this observer from updates to the query cache. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) @@ -56,6 +87,12 @@ be used. 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). + + +### Result properties + +Built from [`QueryObserverBaseResult`](../interfaces/QueryObserverBaseResult.md#properties). See the type above for what it changes. + ## Remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request diff --git a/docs/framework/solid/reference/functions/QueryClientProvider.md b/docs/framework/solid/reference/functions/QueryClientProvider.md index 39bbf4c14b2..97429d9f6c0 100644 --- a/docs/framework/solid/reference/functions/QueryClientProvider.md +++ b/docs/framework/solid/reference/functions/QueryClientProvider.md @@ -22,6 +22,15 @@ comes back online). The `client` to provide, and the `children` that get access to it. + + +#### `props` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `children?` | `JSX.Element` | The components that get access to the provided `QueryClient`. | +| `client` | [`QueryClient`](../classes/QueryClient.md) | **Required** The `QueryClient` instance to provide. | + ## Returns `Element` diff --git a/docs/framework/solid/reference/functions/dehydrate.md b/docs/framework/solid/reference/functions/dehydrate.md index 7db25e95915..8653ce08798 100644 --- a/docs/framework/solid/reference/functions/dehydrate.md +++ b/docs/framework/solid/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/solid/reference/functions/hydrate.md b/docs/framework/solid/reference/functions/hydrate.md index bfd2c2f0770..17c0afeb896 100644 --- a/docs/framework/solid/reference/functions/hydrate.md +++ b/docs/framework/solid/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | `MutationOptions`\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | `QueryOptions`\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/solid/reference/functions/infiniteQueryOptions.md b/docs/framework/solid/reference/functions/infiniteQueryOptions.md index 627383135e5..f111739cb66 100644 --- a/docs/framework/solid/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/solid/reference/functions/infiniteQueryOptions.md @@ -5,6 +5,20 @@ redirect_from: - framework/solid/reference/infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: InfiniteQueryOptions & object): InfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: InfiniteQueryOptions & object): InfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +- [`InfiniteQueryOptions` → `InfiniteQueryOptions`](#call-signature-1): 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. +- [`InfiniteQueryOptions` → `InfiniteQueryOptions`](#call-signature-2): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -91,6 +105,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -176,3 +192,33 @@ function Comments(props: { postId: string }) { ) } ``` + + + +## Parameters + +### options + +[`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` + +The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + + + +#### `options` properties + +Built from [`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +[`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\> + +The same options object, typed so that `queryKey` carries the inferred data type. + + + +### Result properties + +Built from [`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md#properties), [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md#properties). See the type above for what it changes. diff --git a/docs/framework/solid/reference/functions/matchMutation.md b/docs/framework/solid/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/solid/reference/functions/matchMutation.md +++ b/docs/framework/solid/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/solid/reference/functions/matchQuery.md b/docs/framework/solid/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/solid/reference/functions/matchQuery.md +++ b/docs/framework/solid/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/solid/reference/functions/mutationOptions.md b/docs/framework/solid/reference/functions/mutationOptions.md index 2a8ac1eb3c5..55506522aaa 100644 --- a/docs/framework/solid/reference/functions/mutationOptions.md +++ b/docs/framework/solid/reference/functions/mutationOptions.md @@ -5,6 +5,20 @@ redirect_from: - framework/solid/reference/mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): 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`. +- [`Omit` → `Omit`](#call-signature-2): 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 target the mutation via a `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, such as `status`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -74,6 +88,8 @@ function SavingIndicator() { } ``` + + ## Call Signature ```ts @@ -142,3 +158,34 @@ function CreatePost() { return } ``` + + + +## Parameters + +### options + +`Omit`\<[`MutationOptions`](../interfaces/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The mutation options to use, identical to what you'd pass to `useMutation`, without a +`mutationKey`. + + + +#### `options` properties + +Built from [`MutationOptions`](../interfaces/MutationOptions.md#properties). See the type above for what it changes. + + + +## Returns + +`Omit`\<[`MutationOptions`](../interfaces/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + + + +### Result properties + +Built from [`MutationOptions`](../interfaces/MutationOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/solid/reference/functions/noop.md b/docs/framework/solid/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/solid/reference/functions/noop.md +++ b/docs/framework/solid/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/solid/reference/functions/queryOptions.md b/docs/framework/solid/reference/functions/queryOptions.md index 618f50a2e42..6e69bc1e856 100644 --- a/docs/framework/solid/reference/functions/queryOptions.md +++ b/docs/framework/solid/reference/functions/queryOptions.md @@ -5,6 +5,20 @@ redirect_from: - framework/solid/reference/queryOptions --- +## Overview + +```ts +function queryOptions(options: QueryOptions & object): QueryOptions & object & QueryKeyWithDataTag; +function queryOptions(options: QueryOptions & object): QueryOptions & object & QueryKeyWithDataTag; +``` + +- [`QueryOptions` → `QueryOptions`](#call-signature-1): 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. +- [`QueryOptions` → `QueryOptions`](#call-signature-2): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -84,6 +98,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -159,3 +175,33 @@ function Post(props: { id: string }) { ) } ``` + + + +## Parameters + +### options + +[`QueryOptions`](../interfaces/QueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` + +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`. + + + +#### `options` properties + +Built from [`QueryOptions`](../interfaces/QueryOptions.md#properties). See the type above for what it changes. + + + +## Returns + +[`QueryOptions`](../interfaces/QueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, `TQueryFnData`, `TError`\> + +The same options object, typed so that `queryKey` carries the inferred data type. + + + +### Result properties + +Built from [`QueryOptions`](../interfaces/QueryOptions.md#properties), [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md#properties). See the type above for what it changes. diff --git a/docs/framework/solid/reference/functions/useInfiniteQuery.md b/docs/framework/solid/reference/functions/useInfiniteQuery.md index b88fca4fe3c..a0626a8ce2e 100644 --- a/docs/framework/solid/reference/functions/useInfiniteQuery.md +++ b/docs/framework/solid/reference/functions/useInfiniteQuery.md @@ -5,6 +5,20 @@ redirect_from: - framework/solid/reference/useInfiniteQuery --- +## Overview + +```ts +function useInfiniteQuery(options: DefinedInitialDataInfiniteOptions, queryClient?: Accessor): DefinedUseInfiniteQueryResult; +function useInfiniteQuery(options: UndefinedInitialDataInfiniteOptions, queryClient?: Accessor): UseInfiniteQueryResult; +``` + +- [`DefinedInitialDataInfiniteOptions` → `DefinedUseInfiniteQueryResult`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UndefinedInitialDataInfiniteOptions` → `UseInfiniteQueryResult`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -105,6 +119,8 @@ function Projects() { } ``` + + ## Call Signature ```ts @@ -257,3 +273,78 @@ function Projects() { ) } ``` + + + +## Parameters + +### options + +[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> + +An accessor returning the [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything +you can pass to `useInfiniteQuery`. + + + +#### `options` properties + +Built from [`InfiniteQueryOptions`](../interfaces/InfiniteQueryOptions.md#properties). See the type above for what it changes. + +### queryClient? + +`Accessor`\<[`QueryClient`](../classes/QueryClient.md)\> + +An accessor for 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 `fetchNextPage`, `fetchPreviousPage`, +`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and +`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default +`InfiniteData` shape. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. | +| `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `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). | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. | +| `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. | +| `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. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/solid/reference/functions/useIsFetching.md b/docs/framework/solid/reference/functions/useIsFetching.md index a6fe172f21d..9005dfdedb0 100644 --- a/docs/framework/solid/reference/functions/useIsFetching.md +++ b/docs/framework/solid/reference/functions/useIsFetching.md @@ -22,6 +22,12 @@ in the background (useful for app-wide loading indicators). An accessor returning the [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries. + + +#### `filters` properties + +Built from [`QueryFilters`](../interfaces/QueryFilters.md#properties). See the type above for what it changes. + ### queryClient? `Accessor`\<[`QueryClient`](../classes/QueryClient.md)\> diff --git a/docs/framework/solid/reference/functions/useIsMutating.md b/docs/framework/solid/reference/functions/useIsMutating.md index c8481f9bd0f..41bf2870f20 100644 --- a/docs/framework/solid/reference/functions/useIsMutating.md +++ b/docs/framework/solid/reference/functions/useIsMutating.md @@ -22,6 +22,12 @@ The `useIsMutating` primitive returns the `number` of mutations that your applic An accessor returning the [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations. + + +#### `filters` properties + +Built from [`MutationFilters`](../interfaces/MutationFilters.md#properties). See the type above for what it changes. + ### queryClient? `Accessor`\<[`QueryClient`](../classes/QueryClient.md)\> diff --git a/docs/framework/solid/reference/functions/useMutation.md b/docs/framework/solid/reference/functions/useMutation.md index 90a80a60001..ae67b39f184 100644 --- a/docs/framework/solid/reference/functions/useMutation.md +++ b/docs/framework/solid/reference/functions/useMutation.md @@ -40,6 +40,12 @@ Unlike queries, mutations are typically used to create/update/delete data or per An accessor returning the [UseMutationOptions](../type-aliases/UseMutationOptions.md) to use. + + +#### `options` properties + +Built from [`MutationOptions`](../interfaces/MutationOptions.md#properties). See the type above for what it changes. + ### queryClient? `Accessor`\<[`QueryClient`](../classes/QueryClient.md)\> @@ -57,6 +63,12 @@ mutation definition. Hook-level callbacks (passed to `options`) fire for every m 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. + + +### Result properties + +Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes. + ## Examples ```tsx diff --git a/docs/framework/solid/reference/functions/useQuery.md b/docs/framework/solid/reference/functions/useQuery.md index 87f4f313b6d..e2640b60626 100644 --- a/docs/framework/solid/reference/functions/useQuery.md +++ b/docs/framework/solid/reference/functions/useQuery.md @@ -5,6 +5,20 @@ redirect_from: - framework/solid/reference/useQuery --- +## Overview + +```ts +function useQuery(options: UndefinedInitialDataOptions, queryClient?: () => QueryClient): UseQueryResult; +function useQuery(options: DefinedInitialDataOptions, queryClient?: () => QueryClient): DefinedUseQueryResult; +``` + +- [`UndefinedInitialDataOptions` → `UseQueryResult`](#call-signature-1): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it — `enabled: false` skips the initial fetch. +- [`DefinedInitialDataOptions` → `DefinedUseQueryResult`](#call-signature-2): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it — `enabled: false` skips the initial fetch. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -213,6 +227,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -299,3 +315,70 @@ function Posts() { ) } ``` + + + +## Parameters + +### options + +[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +An accessor returning the [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can +pass to `useQuery`, with `initialData` set. + + + +#### `options` properties + +Built from [`QueryOptions`](../interfaces/QueryOptions.md#properties). See the type above for what it changes. + +### queryClient? + +() => [`QueryClient`](../classes/QueryClient.md) + +An accessor for 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, as a Solid store, 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. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/svelte/reference/functions/createInfiniteQuery.md b/docs/framework/svelte/reference/functions/createInfiniteQuery.md index 88ceaad515b..eb46d70e8be 100644 --- a/docs/framework/svelte/reference/functions/createInfiniteQuery.md +++ b/docs/framework/svelte/reference/functions/createInfiniteQuery.md @@ -3,6 +3,22 @@ id: createInfiniteQuery title: createInfiniteQuery --- +## Overview + +```ts +function createInfiniteQuery(options: Accessor>, queryClient?: Accessor): DefinedCreateInfiniteQueryResult; +function createInfiniteQuery(options: Accessor>, queryClient?: Accessor): CreateInfiniteQueryResult; +function createInfiniteQuery(options: Accessor>, queryClient?: Accessor): CreateInfiniteQueryResult; +``` + +- [`DefinedInitialDataInfiniteOptions` → `DefinedCreateInfiniteQueryResult`](#call-signature-1): The options for `createInfiniteQuery` are identical to `createQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`UndefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryResult`](#call-signature-2): The options for `createInfiniteQuery` are identical to `createQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`CreateInfiniteQueryOptions` → `CreateInfiniteQueryResult`](#call-signature-3): The options for `createInfiniteQuery` are identical to `createQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -66,6 +82,8 @@ to page through the query. [infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `createInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + + ## Call Signature ```ts @@ -129,6 +147,8 @@ to page through the query. [infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `createInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + + ## Call Signature ```ts @@ -272,3 +292,107 @@ sentinel element after the list:
{/if} ``` + + + +## Parameters + +### options + +[`Accessor`](../type-aliases/Accessor.md)\<[`CreateInfiniteQueryOptions`](../type-aliases/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\> + +The [CreateInfiniteQueryOptions](../type-aliases/CreateInfiniteQueryOptions.md) to use — everything you can pass to +`createInfiniteQuery`, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `getNextPageParam` | (`lastPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `lastPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of `hasNextPage`. | +| `getPreviousPageParam?` | (`firstPage`: `TQueryFnData`, `allPages`: `TQueryFnData`[], `firstPageParam`: `TPageParam`, `allPageParams`: `TPageParam`[]) => `TPageParam` \| `null` \| `undefined` | `undefined` | This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. | +| `initialData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| () => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `initialPageParam` | `TPageParam` | `undefined` | The page param to start from when an infinite query has no pages yet. It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the value returned by `getNextPageParam` or `getPreviousPageParam`. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| (`previousData`: \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<[`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\> \| `undefined`) => \| [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: [`InfiniteData`](../interfaces/InfiniteData.md)) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\> + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + + + +## Returns + +[`CreateInfiniteQueryResult`](../type-aliases/CreateInfiniteQueryResult.md)\<`TData`, `TError`\> + +The current query result, plus `fetchNextPage`/`fetchPreviousPage`/`hasNextPage`/`hasPreviousPage` +to page through the query. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchNextPage` | (`options?`: [`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the next "page" of results. | +| `fetchPreviousPage` | (`options?`: [`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)) => `Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\> | This function allows you to fetch the previous "page" of results. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `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). | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| `isFetchingNextPage` | `boolean` | Will be `true` while fetching the next page with `fetchNextPage`. | +| `isFetchingPreviousPage` | `boolean` | Will be `true` while fetching the previous page with `fetchPreviousPage`. | +| `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. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/svelte/reference/functions/createMutation.md b/docs/framework/svelte/reference/functions/createMutation.md index c3f6ab66131..fd1bded104a 100644 --- a/docs/framework/svelte/reference/functions/createMutation.md +++ b/docs/framework/svelte/reference/functions/createMutation.md @@ -39,6 +39,12 @@ Unlike queries, mutations are typically used to create/update/delete data or per The [CreateMutationOptions](../type-aliases/CreateMutationOptions.md) to use, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive. + + +#### `options` properties + +Built from [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md#properties). See the type above for what it changes. + ### queryClient? [`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\> @@ -55,6 +61,12 @@ argument, useful for triggering call-site side effects (e.g. navigation) without mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've made. + + +### Result properties + +Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes. + ## See [mutationOptions](mutationOptions.md) to share these options across multiple `createMutation` call sites, or to look diff --git a/docs/framework/svelte/reference/functions/createQuery.md b/docs/framework/svelte/reference/functions/createQuery.md index 020e8490d92..d3c2148d67b 100644 --- a/docs/framework/svelte/reference/functions/createQuery.md +++ b/docs/framework/svelte/reference/functions/createQuery.md @@ -3,6 +3,22 @@ id: createQuery title: createQuery --- +## Overview + +```ts +function createQuery(options: Accessor>, queryClient?: Accessor): DefinedCreateQueryResult; +function createQuery(options: Accessor>, queryClient?: Accessor): CreateQueryResult; +function createQuery(options: Accessor>, queryClient?: Accessor): CreateQueryResult; +``` + +- [`DefinedInitialDataOptions` → `DefinedCreateQueryResult`](#call-signature-1): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it — `enabled: false` skips the initial fetch. +- [`UndefinedInitialDataOptions` → `CreateQueryResult`](#call-signature-2): Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key. The query runs when the options call for it — `enabled: false` skips the initial fetch. +- [`CreateQueryOptions` → `CreateQueryResult`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known — for example, an object typed as [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) rather than an object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -88,6 +104,8 @@ since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived ``` + + ## Call Signature ```ts @@ -194,6 +212,8 @@ The same query, checking `isPending`/`isError` instead of `status` — pick whic {/if} ``` + + ## Call Signature ```ts @@ -353,3 +373,97 @@ Paginated data, keeping the previous page's data visible while the next page loa Next Page ``` + + + +## Parameters + +### options + +[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\> + +The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use — everything you can pass to `createQuery`, wrapped +in an [Accessor](../type-aliases/Accessor.md) so options can be reactive. + + + +#### `options` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `enabled?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `true` | Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the `refetch` method returned from the `useQuery` instance. Accepts a boolean or function that returns a boolean. | +| `gcTime?` | `number` | `undefined` | 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. Setting it to `Infinity` will disable garbage collection. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see `timeoutManager.setTimeoutProvider` for a workaround. | +| `initialData?` | `TQueryData` \| () => `TQueryData` \| `undefined` | `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. | +| `initialDataUpdatedAt?` | `number` \| () => `number` \| `undefined` | `undefined` | If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. | +| `maxPages?` | `number` | `undefined` | Maximum number of pages to store in the data of an infinite query. | +| `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on each query. Use this property to pass information that can be used in other places. | +| `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a query is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `notifyOnChangeProps?` | \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `"all"` \| () => \| `"all"` \| ( \| `"error"` \| `"data"` \| `"isError"` \| `"isPending"` \| `"isLoading"` \| `"isLoadingError"` \| `"isRefetchError"` \| `"isSuccess"` \| `"isPlaceholderData"` \| `"status"` \| `"dataUpdatedAt"` \| `"errorUpdatedAt"` \| `"failureCount"` \| `"failureReason"` \| `"errorUpdateCount"` \| `"isFetched"` \| `"isFetchedAfterMount"` \| `"isFetching"` \| `"isInitialLoading"` \| `"isPaused"` \| `"isRefetching"` \| `"isStale"` \| `"isEnabled"` \| `"refetch"` \| `"fetchStatus"` \| `"fetchNextPage"` \| `"fetchPreviousPage"` \| `"hasNextPage"` \| `"hasPreviousPage"` \| `"isFetchNextPageError"` \| `"isFetchingNextPage"` \| `"isFetchPreviousPageError"` \| `"isFetchingPreviousPage"`)[] \| `undefined` | `undefined` | If set, the component will only re-render if any of the listed properties change. When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change. When set to `'all'`, the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to `undefined`, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes. | +| `persister?` | (`queryFn`: (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`NoInfer`\<`TQueryKey`\>, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\>, `context`: `object`, `query`: [`Query`](../classes/Query.md)) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. | +| `placeholderData?` | \| `NonFunctionGuard`\<`TQueryData`\> \| (`previousData`: `NonFunctionGuard`\<`TQueryData`\> \| `undefined`, `previousQuery`: \| [`Query`](../classes/Query.md)\<`NonFunctionGuard`\<`TQueryData`\>, `TError`, `NonFunctionGuard`\<`TQueryData`\>, `TQueryKey`\> \| `undefined`) => `NonFunctionGuard`\<`TQueryData`\> \| `undefined` | `undefined` | If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. | +| `queryFn?` | \| *typeof* [`skipToken`](../variables/skipToken.md) \| (`context`: [`QueryFunctionContext`](../type-aliases/QueryFunctionContext.md)\<`TQueryKey`, `TPageParam`\>) => `TQueryFnData` \| `Promise`\<`TQueryFnData`\> | `undefined` | The function that the query will use to request data. Required, unless a default query function has been set via `queryClient.setQueryDefaults` or `queryClient.setDefaultOptions`. Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md). Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. | +| `queryHash?` | `string` | `undefined` | The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used as the actual cache key internally. | +| `queryKey` | `TQueryKey` & `object` | `undefined` | The query key to use for this query. The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information. The query will automatically update when this key changes (as long as `enabled` is not set to `false`). | +| `queryKeyHashFn?` | (`queryKey`: `TQueryKey`) => `string` | `undefined` | If specified, this function is used to hash the `queryKey` to a string. | +| `refetchInterval?` | \| `number` \| `false` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `false` \| `undefined` | `false` | If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency | +| `refetchIntervalInBackground?` | `boolean` | `false` | If set to `true`, the query will continue to refetch while their tab/window is in the background. | +| `refetchOnMount?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `true` | If set to `true`, the query will refetch on mount if the data is stale. If set to `false`, will disable additional instances of a query to trigger background refetch. 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 latest data and query to compute the value | +| `refetchOnReconnect?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `undefined` | 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 latest data and query to compute the value. Defaults to `true` unless `networkMode` is `'always'`. | +| `refetchOnWindowFocus?` | \| `boolean` \| `"always"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` \| `"always"` | `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 latest data and query to compute the value. | +| `retry?` | \| `number` \| `false` \| `true` \| (`failureCount`: `number`, `error`: `TError`) => `boolean` | `undefined` | If `false`, failed queries will not retry by default. If `true`, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. Defaults to `3` on the client and `0` on the server. | +| `retryDelay?` | `number` \| (`failureCount`: `number`, `error`: `TError`) => `number` | `undefined` | 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. Defaults to a function that applies exponential backoff, capped at 30 seconds. | +| `retryOnMount?` | \| `false` \| `true` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `true` | If set to `false`, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value. | +| `select?` | (`data`: `TQueryData`) => `TData` | `undefined` | 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, memoize the function so its reference stays stable across calls. | +| `staleTime?` | \| `number` \| `"static"` \| (`query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `number` \| `"static"` | `0` | The time in milliseconds after data is considered stale. If set to `Infinity`, the data will never be considered stale. If set to `'static'`, the data will never be considered stale. If set to a function, the function will be executed with the query to compute a `staleTime`. | +| `structuralSharing?` | `boolean` \| (`oldData`: `unknown`, `newData`: `unknown`) => `unknown` | `true` | Set this to `false` to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. | +| `suspense?` | `boolean` | `false` | If set to `true`, the query will suspend when `status === 'pending'` and throw errors when `status === 'error'`. | +| `throwOnError?` | \| `false` \| `true` \| (`error`: `TError`, `query`: [`Query`](../classes/Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>) => `boolean` | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. If set to `false` and `suspense` is `false`, errors are returned as state. 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`). | + +### queryClient? + +[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\> + +Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will +be used. + + + +## Returns + +[`CreateQueryResult`](../type-aliases/CreateQueryResult.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. + + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `data` | `TData` \| `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` | `TError` \| `null` | The error object for the query, if an error was thrown. - Defaults to `null`. | +| `errorUpdateCount` | `number` | The sum of all errors. | +| `errorUpdatedAt` | `number` | The timestamp for when the query most recently returned the `status` as `"error"`. | +| `failureCount` | `number` | The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. | +| `failureReason` | `TError` \| `null` | The failure reason for the query retry. - Reset to `null` when the query succeeds. | +| `fetchStatus` | `"fetching"` \| `"paused"` \| `"idle"` | The fetch status of the query. - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - `paused`: The query wanted to fetch, but has been `paused`. - `idle`: The query is not fetching. - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. | +| `isEnabled` | `boolean` | `true` if this observer is enabled, `false` otherwise. | +| `isError` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query attempt resulted in an error. | +| `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. | +| `isFetching` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. | +| ~~`isInitialLoading`~~ | `boolean` | **Deprecated** `isInitialLoading` is being deprecated in favor of `isLoading` and will be removed in the next major version. | +| `isLoading` | `boolean` | Is `true` whenever the first fetch for a query is in-flight. - Is the same as `isFetching && isPending`. | +| `isLoadingError` | `boolean` | Will be `true` if the query failed while fetching for the first time. | +| `isPaused` | `boolean` | A derived boolean from the `fetchStatus` variable, provided for convenience. - The query wanted to fetch, but has been `paused`. | +| `isPending` | `boolean` | Will be `pending` if there's no cached data and no query attempt was finished yet. | +| `isPlaceholderData` | `boolean` | Will be `true` if the data shown is the placeholder data. | +| `isRefetchError` | `boolean` | Will be `true` if the query failed while refetching. | +| `isRefetching` | `boolean` | Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - Is the same as `isFetching && !isPending`. | +| `isStale` | `boolean` | Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. | +| `isSuccess` | `boolean` | A derived boolean from the `status` variable, provided for convenience. - `true` if the query has received a response with no errors and is ready to display its data. | +| `refetch` | (`options?`: [`RefetchOptions`](../interfaces/RefetchOptions.md)) => `Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\> | A function to manually refetch the query. | +| `status` | `"error"` \| `"pending"` \| `"success"` | The status of the query. - 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. - `success` if the query has received a response with no errors and is ready to display its data. | diff --git a/docs/framework/svelte/reference/functions/dehydrate.md b/docs/framework/svelte/reference/functions/dehydrate.md index 53b1fc5eba7..e01b3cf74ef 100644 --- a/docs/framework/svelte/reference/functions/dehydrate.md +++ b/docs/framework/svelte/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/svelte/reference/functions/hydrate.md b/docs/framework/svelte/reference/functions/hydrate.md index 5e250b9da2b..e160e90a332 100644 --- a/docs/framework/svelte/reference/functions/hydrate.md +++ b/docs/framework/svelte/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/svelte/reference/functions/infiniteQueryOptions.md b/docs/framework/svelte/reference/functions/infiniteQueryOptions.md index 3b7f41704ce..fc5bf1d348f 100644 --- a/docs/framework/svelte/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/svelte/reference/functions/infiniteQueryOptions.md @@ -3,6 +3,20 @@ id: infiniteQueryOptions title: infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: DefinedInitialDataInfiniteOptions): CreateInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: UndefinedInitialDataInfiniteOptions): CreateInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; +``` + +- [`DefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryOptions`](#call-signature-1): You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`. These options can be shared across `createInfiniteQuery` calls and imperative APIs such as `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for. +- [`UndefinedInitialDataInfiniteOptions` → `CreateInfiniteQueryOptions`](#call-signature-2): You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`. These options can be shared across `createInfiniteQuery` calls and imperative APIs such as `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -89,6 +103,8 @@ visible alongside the error: ``` + + ## Call Signature ```ts @@ -176,3 +192,34 @@ A parameterized factory, so the same options object can be reused per `postId`: {/if} ``` + + + +## 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 +`createInfiniteQuery`. + + + +#### `options` properties + +Built from [`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md#properties). See the type above for what it changes. + + + +## Returns + +[`CreateInfiniteQueryOptions`](../type-aliases/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\> + +The same options object, typed so that `queryKey` carries the inferred data type. + + + +### Result properties + +Built from [`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md#properties), [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md#properties). See the type above for what it changes. diff --git a/docs/framework/svelte/reference/functions/matchMutation.md b/docs/framework/svelte/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/svelte/reference/functions/matchMutation.md +++ b/docs/framework/svelte/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/svelte/reference/functions/matchQuery.md b/docs/framework/svelte/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/svelte/reference/functions/matchQuery.md +++ b/docs/framework/svelte/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/svelte/reference/functions/mutationOptions.md b/docs/framework/svelte/reference/functions/mutationOptions.md index 37d81ef73f9..e8ccc3b1a99 100644 --- a/docs/framework/svelte/reference/functions/mutationOptions.md +++ b/docs/framework/svelte/reference/functions/mutationOptions.md @@ -3,6 +3,20 @@ id: mutationOptions title: mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): You can generally pass everything to `mutationOptions` that you can also pass to `createMutation`. This overload requires `mutationKey`, so the resulting options can be looked up elsewhere (e.g. with `useMutationState`). +- [`Omit` → `Omit`](#call-signature-2): You can generally pass everything to `mutationOptions` that you can also pass to `createMutation`. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -73,6 +87,8 @@ Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "savi {/if} ``` + + ## Call Signature ```ts @@ -134,3 +150,33 @@ The same options object. ``` + + + +## Parameters + +### options + +`Omit`\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The options to use — everything you can pass to `createMutation`. + + + +#### `options` properties + +Built from [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md#properties). See the type above for what it changes. + + + +## Returns + +`Omit`\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object. + + + +### Result properties + +Built from [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md#properties). See the type above for what it changes. diff --git a/docs/framework/svelte/reference/functions/noop.md b/docs/framework/svelte/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/svelte/reference/functions/noop.md +++ b/docs/framework/svelte/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/svelte/reference/functions/queryOptions.md b/docs/framework/svelte/reference/functions/queryOptions.md index 323e99cb584..ad3b8a0cc07 100644 --- a/docs/framework/svelte/reference/functions/queryOptions.md +++ b/docs/framework/svelte/reference/functions/queryOptions.md @@ -3,6 +3,20 @@ id: queryOptions title: queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialDataOptions): CreateQueryOptions & object & QueryKeyWithDataTag; +function queryOptions(options: UndefinedInitialDataOptions): CreateQueryOptions & object & QueryKeyWithDataTag; +``` + +- [`DefinedInitialDataOptions` → `CreateQueryOptions`](#call-signature-1): You can generally pass everything to `queryOptions` that you can also pass to `createQuery`. These options can be shared across `createQuery` calls and imperative APIs such as `queryClient.query`. `options.queryKey` is required and is the query key to generate options for. +- [`UndefinedInitialDataOptions` → `CreateQueryOptions`](#call-signature-2): You can generally pass everything to `queryOptions` that you can also pass to `createQuery`. These options can be shared across `createQuery` calls and imperative APIs such as `queryClient.query`. `options.queryKey` is required and is the query key to generate options for. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -82,6 +96,8 @@ The same options object, typed so that `queryKey` carries the inferred data type ``` + + ## Call Signature ```ts @@ -156,3 +172,33 @@ A parameterized factory, so the same options object can be reused per `id`:

{query.data.title}

{/if} ``` + + + +## Parameters + +### options + +[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `createQuery`. + + + +#### `options` properties + +Built from [`QueryObserverOptions`](../interfaces/QueryObserverOptions.md#properties). See the type above for what it changes. + + + +## Returns + +[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, `TQueryFnData`, `TError`\> + +The same options object, typed so that `queryKey` carries the inferred data type. + + + +### Result properties + +Built from [`QueryObserverOptions`](../interfaces/QueryObserverOptions.md#properties), [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md#properties). See the type above for what it changes. diff --git a/docs/framework/svelte/reference/functions/useHydrate.md b/docs/framework/svelte/reference/functions/useHydrate.md index 8d016c1b40d..53d7c4a83cc 100644 --- a/docs/framework/svelte/reference/functions/useHydrate.md +++ b/docs/framework/svelte/reference/functions/useHydrate.md @@ -31,6 +31,17 @@ The dehydrated state to hydrate into the cache, as produced by `dehydrate`. [HydrateOptions](../interfaces/HydrateOptions.md) to control the hydration. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | [`MutationOptions`](../interfaces/MutationOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | [`QueryOptions`](../interfaces/QueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/svelte/reference/functions/useIsFetching.md b/docs/framework/svelte/reference/functions/useIsFetching.md index ffa958bc9f6..e50faa200ee 100644 --- a/docs/framework/svelte/reference/functions/useIsFetching.md +++ b/docs/framework/svelte/reference/functions/useIsFetching.md @@ -21,6 +21,19 @@ fetching in the background (useful for app-wide loading indicators). [QueryFilters](../interfaces/QueryFilters.md) to narrow down which queries to count. Omit to count every fetching query. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/svelte/reference/functions/useIsMutating.md b/docs/framework/svelte/reference/functions/useIsMutating.md index f666766749b..3143a8b2dc2 100644 --- a/docs/framework/svelte/reference/functions/useIsMutating.md +++ b/docs/framework/svelte/reference/functions/useIsMutating.md @@ -20,6 +20,17 @@ running (useful for app-wide loading indicators). [MutationFilters](../interfaces/MutationFilters.md) to narrow down which mutations to count. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/svelte/reference/functions/useMutationState.md b/docs/framework/svelte/reference/functions/useMutationState.md index 4937d3e7a95..0bbde650c83 100644 --- a/docs/framework/svelte/reference/functions/useMutationState.md +++ b/docs/framework/svelte/reference/functions/useMutationState.md @@ -32,6 +32,15 @@ state. The `filters` to narrow down matched mutations, and an optional `select` to transform the mutation state. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `filters?` | [`MutationFilters`](../interfaces/MutationFilters.md) | The filters that select the mutations to return the state of. | +| `select?` | (`mutation`: `TMutation`) => `TResult` | Maps each matching mutation to the value returned for it. Defaults to the mutation's `state`. | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/vue/reference/functions/dehydrate.md b/docs/framework/vue/reference/functions/dehydrate.md index 7db25e95915..8653ce08798 100644 --- a/docs/framework/vue/reference/functions/dehydrate.md +++ b/docs/framework/vue/reference/functions/dehydrate.md @@ -30,12 +30,32 @@ The client whose cache is dehydrated. Controls which queries and mutations are included and how their data and errors are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `serializeData?` | `TransformerFn` | Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. | +| `shouldDehydrateMutation?` | (`mutation`: [`Mutation`](../classes/Mutation.md)) => `boolean` | Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. | +| `shouldDehydrateQuery?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. | +| `shouldRedactErrors?` | (`error`: `unknown`) => `boolean` | Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the given error, in which case the original error is kept. | + ## Returns [`DehydratedState`](../interfaces/DehydratedState.md) The dehydrated state, with the included `queries` and `mutations`. + + +### Result properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `mutations` | `DehydratedMutation`[] | The dehydrated mutations, by default only the paused ones. | +| `queries` | `DehydratedQuery`[] | The dehydrated queries, by default only the successful ones. | + ## Example ```ts diff --git a/docs/framework/vue/reference/functions/hydrate.md b/docs/framework/vue/reference/functions/hydrate.md index bfd2c2f0770..17c0afeb896 100644 --- a/docs/framework/vue/reference/functions/hydrate.md +++ b/docs/framework/vue/reference/functions/hydrate.md @@ -34,6 +34,12 @@ The client whose cache is restored into. The dehydrated state, e.g. produced by `dehydrate` on the server. + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) @@ -41,6 +47,17 @@ The dehydrated state, e.g. produced by `dehydrate` on the server. `defaultOptions` merged into every restored query and mutation (on top of the client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + + +#### `options` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `defaultOptions?` | `object` | Options applied to the queries and mutations restored from the dehydrated state. | +| `defaultOptions.deserializeData?` | `TransformerFn` | Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. | +| `defaultOptions.mutations?` | `MutationOptions`\<`unknown`, `Error`, `unknown`, `unknown`\> | Default options merged into every mutation restored from the dehydrated state. | +| `defaultOptions.queries?` | `QueryOptions`\<`unknown`, `Error`, `unknown`, readonly `unknown`[], `never`\> | Default options merged into every query restored from the dehydrated state. | + ## Returns `void` diff --git a/docs/framework/vue/reference/functions/infiniteQueryOptions.md b/docs/framework/vue/reference/functions/infiniteQueryOptions.md index ef8c037af75..10808085a95 100644 --- a/docs/framework/vue/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/vue/reference/functions/infiniteQueryOptions.md @@ -5,6 +5,20 @@ redirect_from: - framework/vue/reference/infiniteQueryOptions --- +## Overview + +```ts +function infiniteQueryOptions(options: UndefinedInitialDataInfiniteOptions): UndefinedInitialDataInfiniteOptions & QueryKeyWithDataTag, TError>; +function infiniteQueryOptions(options: DefinedInitialDataInfiniteOptions): DefinedInitialDataInfiniteOptions & QueryKeyWithDataTag, TError>; +``` + +- [`UndefinedInitialDataInfiniteOptions` → `UndefinedInitialDataInfiniteOptions`](#call-signature-1): 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. +- [`DefinedInitialDataInfiniteOptions` → `DefinedInitialDataInfiniteOptions`](#call-signature-2): 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. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -75,6 +89,8 @@ const { data, isError, error, fetchNextPage } = useInfiniteQuery(projectsOptions ``` + + ## Call Signature ```ts @@ -150,3 +166,22 @@ const projectsOptions = infiniteQueryOptions({ const { data, isError, error } = useInfiniteQuery(projectsOptions) ``` + + + +## 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 + +[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\> + +The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/docs/framework/vue/reference/functions/matchMutation.md b/docs/framework/vue/reference/functions/matchMutation.md index af337cdbec0..b12d3b9565c 100644 --- a/docs/framework/vue/reference/functions/matchMutation.md +++ b/docs/framework/vue/reference/functions/matchMutation.md @@ -21,6 +21,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i The filters to check the mutation against. + + +#### `filters` properties + +| Property | Type | Description | +| ------ | ------ | ------ | +| `exact?` | `boolean` | Match mutation key exactly | +| `mutationKey?` | readonly `unknown`[] | Include mutations matching this mutation key | +| `predicate?` | (`mutation`: [`Mutation`](../classes/Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>) => `boolean` | Include mutations matching this predicate function | +| `status?` | `"error"` \| `"pending"` \| `"success"` \| `"idle"` | Filter by mutation status | + ### mutation [`Mutation`](../classes/Mutation.md)\<`any`, `any`\> diff --git a/docs/framework/vue/reference/functions/matchQuery.md b/docs/framework/vue/reference/functions/matchQuery.md index 312065fa2f2..e1cdd4ee789 100644 --- a/docs/framework/vue/reference/functions/matchQuery.md +++ b/docs/framework/vue/reference/functions/matchQuery.md @@ -20,6 +20,19 @@ Every filter that is specified must match; filters that are left unspecified are The filters to check the query against. + + +#### `filters` properties + +| Property | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `exact?` | `boolean` | `undefined` | Match query key exactly | +| `fetchStatus?` | `"fetching"` \| `"paused"` \| `"idle"` | `undefined` | Include queries matching their fetchStatus | +| `predicate?` | (`query`: [`Query`](../classes/Query.md)) => `boolean` | `undefined` | Include queries matching this predicate function | +| `queryKey?` | `TQueryKey` \| `TuplePrefixes`\<`TQueryKey`\> | `undefined` | Include queries matching this query key | +| `stale?` | `boolean` | `undefined` | Include or exclude stale queries | +| `type?` | `QueryTypeFilter` | `'all'` | Filter to active queries, inactive queries or all queries | + ### query [`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\> diff --git a/docs/framework/vue/reference/functions/mutationOptions.md b/docs/framework/vue/reference/functions/mutationOptions.md index 1242b713b32..d9ed20ad608 100644 --- a/docs/framework/vue/reference/functions/mutationOptions.md +++ b/docs/framework/vue/reference/functions/mutationOptions.md @@ -5,6 +5,24 @@ redirect_from: - framework/vue/reference/mutationOptions --- +## Overview + +```ts +function mutationOptions(options: WithRequired, "mutationKey">): WithRequired, "mutationKey">; +function mutationOptions(options: () => WithRequired, "mutationKey">): () => WithRequired, "mutationKey">; +function mutationOptions(options: Omit, "mutationKey">): Omit, "mutationKey">; +function mutationOptions(options: () => Omit, "mutationKey">): () => Omit, "mutationKey">; +``` + +- [`WithRequired` → `WithRequired`](#call-signature-1): 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`. +- [`WithRequired` → `WithRequired`](#call-signature-2): Same as the plain-object overload with a required `mutationKey`, but for options that close over reactive state (`ref`s read inside the function body). Wrap them in a getter so `useMutation` and the other consumers always read the current values instead of the ones captured when the options were created. +- [`Omit` → `Omit`](#call-signature-3): 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 target the mutation via a `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, such as `status`. +- [`Omit` → `Omit`](#call-signature-4): Same as the plain-object overload without a `mutationKey`, but for options that close over reactive state (`ref`s read inside the function body). Wrap them in a getter so `useMutation` and the other consumers always read the current values instead of the ones captured when the options were created. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -79,6 +97,8 @@ const isCreatingPost = computed(() => creatingPosts.value.length > 0) ``` + + ## Call Signature ```ts @@ -156,6 +176,8 @@ const mutation = useMutation(createPostOptions) ``` + + ## Call Signature ```ts @@ -228,6 +250,8 @@ const mutation = useMutation(createPostOptions) ``` + + ## Call Signature ```ts @@ -303,3 +327,28 @@ const mutation = useMutation(createPostOptions) ``` + + + +## Parameters + +### options + +() => `Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +A function returning the mutation options to use, without a `mutationKey`, re-evaluated on +demand. + + + +## Returns + +A function that returns the same options object, unchanged. + +```ts +(): Omit, "mutationKey">; +``` + +#### Returns + +`Omit`\<[`MutationOptions`](../type-aliases/MutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> diff --git a/docs/framework/vue/reference/functions/noop.md b/docs/framework/vue/reference/functions/noop.md index 5fe4fc5ba99..02331d2a79f 100644 --- a/docs/framework/vue/reference/functions/noop.md +++ b/docs/framework/vue/reference/functions/noop.md @@ -3,6 +3,20 @@ id: noop title: noop --- +## Overview + +```ts +function noop(): void; +function noop(): undefined; +``` + +- [`void`](#call-signature-1): A function that does nothing. +- [`undefined`](#call-signature-2): A function that does nothing. + +See also: [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -17,6 +31,8 @@ A function that does nothing. `void` + + ## Call Signature ```ts @@ -30,3 +46,9 @@ A function that does nothing. ### Returns `undefined` + + + +## Returns + +`undefined` diff --git a/docs/framework/vue/reference/functions/queryOptions.md b/docs/framework/vue/reference/functions/queryOptions.md index 1ee66302494..e55b63a9522 100644 --- a/docs/framework/vue/reference/functions/queryOptions.md +++ b/docs/framework/vue/reference/functions/queryOptions.md @@ -5,6 +5,24 @@ redirect_from: - framework/vue/reference/queryOptions --- +## Overview + +```ts +function queryOptions(options: DefinedInitialQueryOptions): DefinedInitialQueryOptionsWithDataTag; +function queryOptions(options: () => DefinedInitialQueryOptions): () => DefinedInitialQueryOptionsWithDataTag; +function queryOptions(options: UndefinedInitialQueryOptions): UndefinedInitialQueryOptionsWithDataTag; +function queryOptions(options: () => UndefinedInitialQueryOptions): () => UndefinedInitialQueryOptionsWithDataTag; +``` + +- [`DefinedInitialQueryOptions` → `DefinedInitialQueryOptionsWithDataTag`](#call-signature-1): 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. +- [`DefinedInitialQueryOptions` → `DefinedInitialQueryOptionsWithDataTag`](#call-signature-2): Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the function body). Wrap them in a getter so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current values instead of the ones captured when the options were created. +- [`UndefinedInitialQueryOptions` → `UndefinedInitialQueryOptionsWithDataTag`](#call-signature-3): 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. +- [`UndefinedInitialQueryOptions` → `UndefinedInitialQueryOptionsWithDataTag`](#call-signature-4): Same as the plain-object overload, but for options that close over reactive state (`ref`s read inside the function body). Wrap them in a getter so the `queryKey` — and anything else derived from a `ref` — reacts to changes, and so `queryClient` methods like `invalidateQueries`/`fetchQuery` always read the current values instead of the ones captured when the options were created. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -75,6 +93,8 @@ const { data, isError, error } = useQuery(postsOptions) ``` + + ## Call Signature ```ts @@ -149,6 +169,8 @@ const { data } = useQuery(postOptions) ``` + + ## Call Signature ```ts @@ -215,6 +237,8 @@ const { data, isPending, isError, error } = useQuery(postOptions('1')) ``` + + ## Call Signature ```ts @@ -311,3 +335,29 @@ const props = defineProps<{ postId: number | undefined }>() const { data, isLoading, isError, error } = useQuery(postOptions(props.postId)) ``` + + + +## Parameters + +### options + +() => [`UndefinedInitialQueryOptions`](../type-aliases/UndefinedInitialQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> + +A function returning the [UndefinedInitialQueryOptions](../type-aliases/UndefinedInitialQueryOptions.md) to use, re-evaluated on +demand. + + + +## Returns + +A function that returns the same options object, typed so that `queryKey` carries the inferred +data type. + +```ts +(): UndefinedInitialQueryOptionsWithDataTag; +``` + +#### Returns + +[`UndefinedInitialQueryOptionsWithDataTag`](../type-aliases/UndefinedInitialQueryOptionsWithDataTag.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> diff --git a/docs/framework/vue/reference/functions/useInfiniteQuery.md b/docs/framework/vue/reference/functions/useInfiniteQuery.md index d454c6d0c3e..81589b6db88 100644 --- a/docs/framework/vue/reference/functions/useInfiniteQuery.md +++ b/docs/framework/vue/reference/functions/useInfiniteQuery.md @@ -5,6 +5,22 @@ redirect_from: - framework/vue/reference/useInfiniteQuery --- +## Overview + +```ts +function useInfiniteQuery(options: MaybeRefOrGetter>, queryClient?: QueryClient): UseInfiniteQueryReturnType; +function useInfiniteQuery(options: MaybeRefOrGetter>, queryClient?: QueryClient): UseInfiniteQueryReturnType; +function useInfiniteQuery(options: MaybeRefOrGetter>, queryClient?: QueryClient): UseInfiniteQueryReturnType; +``` + +- [`MaybeRefOrGetter` → `UseInfiniteQueryReturnType`](#call-signature-1): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`MaybeRefOrGetter` → `UseInfiniteQueryReturnType`](#call-signature-2): The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. +- [`MaybeRefOrGetter` → `UseInfiniteQueryReturnType`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known — for example, a `ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -103,6 +119,8 @@ const { data, isError, error } = useInfiniteQuery({ ``` + + ## Call Signature ```ts @@ -266,6 +284,8 @@ onUnmounted(() => observer?.disconnect()) ``` + + ## Call Signature ```ts @@ -387,3 +407,30 @@ const { data, isLoading, isError, error } = useInfiniteQuery(() => { ``` + + + +## Parameters + +### options + +`MaybeRefOrGetter`\<[`UseInfiniteQueryOptions`](../type-aliases/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\> + +A `ref`, plain value, or reactive getter resolving to the [UseInfiniteQueryOptions](../type-aliases/UseInfiniteQueryOptions.md) to +use. + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` +will be used. + + + +## Returns + +[`UseInfiniteQueryReturnType`](../type-aliases/UseInfiniteQueryReturnType.md)\<`TData`, `TError`\> + +The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, +`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. diff --git a/docs/framework/vue/reference/functions/usePrefetchQuery.md b/docs/framework/vue/reference/functions/usePrefetchQuery.md index 2a9eca48c4b..9b5adb8d2a2 100644 --- a/docs/framework/vue/reference/functions/usePrefetchQuery.md +++ b/docs/framework/vue/reference/functions/usePrefetchQuery.md @@ -54,6 +54,12 @@ Fire this during render, before a suspense boundary that wraps a component using A `ref`, plain value, or reactive getter resolving to the [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`. + + +#### `options` properties + +Built from [`QueryExecuteOptions`](../interfaces/QueryExecuteOptions.md#properties). See the type above for what it changes. + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/vue/reference/functions/useQuery.md b/docs/framework/vue/reference/functions/useQuery.md index f7124b0f391..ac35121d383 100644 --- a/docs/framework/vue/reference/functions/useQuery.md +++ b/docs/framework/vue/reference/functions/useQuery.md @@ -5,6 +5,22 @@ redirect_from: - framework/vue/reference/useQuery --- +## Overview + +```ts +function useQuery(options: DefinedInitialQueryOptions, queryClient?: QueryClient): UseQueryDefinedReturnType; +function useQuery(options: UndefinedInitialQueryOptions, queryClient?: QueryClient): UseQueryReturnType; +function useQuery(options: MaybeRefOrGetter>, queryClient?: QueryClient): UseQueryReturnType; +``` + +- [`DefinedInitialQueryOptions` → `UseQueryDefinedReturnType`](#call-signature-1): This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). +- [`UndefinedInitialQueryOptions` → `UseQueryReturnType`](#call-signature-2): `enabled` tracks reactive dependencies automatically as a `ref`, a plain value, or a reactive getter (`() => ...`). `queryKey` reacts through a `ref` or a reactive getter for the array itself, or `ref`s and reactive getters as individual entries. Other options are read once when passed as a plain value, and stay reactive when passed as a `ref` or a `computed`. +- [`MaybeRefOrGetter` → `UseQueryReturnType`](#call-signature-3): Fallback overload for options whose `initialData` presence isn't statically known — for example, a `ref`/reactive object built up conditionally, rather than a plain object literal. Prefer one of the other overloads when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -86,6 +102,8 @@ const { data, isError, error } = useQuery({ ``` + + ## Call Signature ```ts @@ -259,6 +277,8 @@ const { data, isPlaceholderData, isError, error } = useQuery({ ``` + + ## Call Signature ```ts @@ -365,3 +385,28 @@ const { data, isLoading, isError, error } = useQuery(() => {

{{ data?.title }}

``` + + + +## Parameters + +### options + +`MaybeRefOrGetter`\<[`UseQueryOptions`](../type-aliases/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryFnData`, `TQueryKey`\>\> + +A `ref`, plain value, or reactive getter resolving to the [UseQueryOptions](../type-aliases/UseQueryOptions.md) to use. + +### queryClient? + +[`QueryClient`](../classes/QueryClient.md) + +Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` +will be used. + + + +## Returns + +[`UseQueryReturnType`](../type-aliases/UseQueryReturnType.md)\<`TData`, `TError`\> + +The current query result, with `data` typed as possibly `undefined`. diff --git a/scripts/generate-docs.ts b/scripts/generate-docs.ts index b111f5b7e7f..485bfe8d156 100644 --- a/scripts/generate-docs.ts +++ b/scripts/generate-docs.ts @@ -210,6 +210,551 @@ async function generatePackageReferenceDocs(pkg: PackageReferenceDocsConfig) { if (pkg.redirectFrom) { await addRedirectFromToFrontmatter(outputDir, pkg.redirectFrom) } + + await addReferenceDetails(outputDir) +} + +// Splits the escaped type arguments (`\\<…\\>`) that follow a type name from the rest of the line. +function splitTypeArguments(rest: string) { + if (!rest.startsWith('\\<')) { + return { typeArguments: undefined, after: rest } + } + let depth = 0 + for (let index = 0; index < rest.length; index++) { + if (rest.startsWith('\\<', index)) { + depth++ + } else if (rest.startsWith('\\>', index) && --depth === 0) { + return { + typeArguments: rest.slice(2, index), + after: rest.slice(index + 2), + } + } + } + return { typeArguments: undefined, after: rest } +} + +// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type +// (with an optional default value), looking through wrappers that only change how the value is +// passed, i.e. aliases like `Accessor = () => T` and inline `() => T`. +// Whether a type alias only changes how its single type argument is passed, e.g. `Accessor = () => T`. +async function isWrapperAlias(outputDir: string, from: string) { + const code = (await readPage(outputDir, from))?.match( + /```ts\ntype \w+<(\w+)> = ([^\n]*);\n```/, + ) + return ( + !!code && + code[2]! + .split(' | ') + .every((member) => member === code[1] || member === `() => ${code[1]}`) + ) +} + +// The type page a `Parameters`/`Returns` type line refers to when the whole line is that one type +// (with an optional default value), looking through wrappers that only change how the value is +// passed, i.e. aliases like `Accessor = () => T` and inline `() => T`. +async function linkedTypePage(outputDir: string, typeLine: string) { + let line = typeLine + for (;;) { + line = line.replace(/^\(\) => /, '') + const link = line.match( + /^\[`\w+`\]\(\.\.\/((?:interfaces|type-aliases)\/\w+)\.md\)/, + ) + if (!link) { + return undefined + } + const { typeArguments, after } = splitTypeArguments( + line.slice(link[0].length), + ) + if (typeArguments && (await isWrapperAlias(outputDir, link[1]!))) { + line = typeArguments + continue + } + return after === '' || after.startsWith(' = ') ? link[1] : undefined + } +} + +// The name of the type a signature's code starts with, looking through the same wrappers. +async function typeNameInCode(outputDir: string, code: string) { + let type = code + for (;;) { + type = type.replace(/^\(\) => /, '') + const name = type.match(/^\w+/)?.[0] + if ( + !name || + type[name.length] !== '<' || + !(await isWrapperAlias(outputDir, `type-aliases/${name}`)) + ) { + return name + } + let depth = 0 + for (let index = name.length; index < type.length; index++) { + if (type[index] === '<') { + depth++ + } else if ( + type[index] === '>' && + type[index - 1] !== '=' && + --depth === 0 + ) { + type = type.slice(name.length + 1, index) + break + } + } + } +} + +// The property table for the first type line that has one. +async function findPropertiesTable( + outputDir: string, + typeLines: Array, +) { + for (const typeLine of typeLines) { + const link = await linkedTypePage(outputDir, typeLine) + const from = link && (await propertiesPage(outputDir, link)) + const table = from && (await readPropertiesTable(outputDir, from)) + if (table) { + return table + } + } + const bases = await findBasePages(outputDir, typeLines) + if (bases.length) { + return `Built from ${bases + .map( + (base) => `[\`${base.split('/').at(-1)}\`](../${base}.md#properties)`, + ) + .join(', ')}. See the type above for what it changes.` + } + return undefined +} + +// Splits a type expression at a top-level separator, outside `<>`, `()`, `{}`, and `[]`. +function splitTopLevel(type: string, separator: string) { + const parts: Array = [] + let depth = 0 + let start = 0 + for (let index = 0; index < type.length; index++) { + const char = type[index]! + if ('<({['.includes(char)) { + depth++ + } else if ( + ')}]'.includes(char) || + (char === '>' && type[index - 1] !== '=') + ) { + depth-- + } else if (depth === 0 && type.startsWith(separator, index)) { + parts.push(type.slice(start, index)) + start = index + separator.length + index += separator.length - 1 + } + } + parts.push(type.slice(start)) + return parts.map((part) => part.trim()).filter(Boolean) +} + +async function typePage(outputDir: string, name: string) { + for (const from of [`interfaces/${name}`, `type-aliases/${name}`]) { + if ((await readPage(outputDir, from)) !== undefined) { + return from + } + } + return undefined +} + +// The pages with a `## Properties` table that a type expression without one is built from: every +// member of an intersection (skipping object literals, which only add properties), and the first type +// argument of a utility that isn't built from one itself, like `Omit<…>`. Returns nothing unless every part is found. +async function basePagesOfType( + outputDir: string, + type: string, + seen: Set, +): Promise> { + const expression = splitTopLevel(type, ' = ')[0]! + .replace(/^[|&]\s*/, '') + .replace(/^\(\) => /, '') + .trim() + const members = splitTopLevel(expression, ' & ').filter( + (member) => member !== 'object' && !member.startsWith('{'), + ) + if (members.length > 1) { + const pages: Array = [] + for (const member of members) { + const memberPages = await basePagesOfType(outputDir, member, seen) + if (!memberPages.length) { + return [] + } + pages.push(...memberPages) + } + return [...new Set(pages)] + } + const reference = members[0]?.match(/^(\w+)(?:<([\s\S]*)>)?$/) + if (!reference) { + return [] + } + const [, name, typeArguments] = reference + const [firstTypeArgument] = typeArguments + ? splitTopLevel(typeArguments, ',') + : [] + const page = await typePage(outputDir, name!) + const pages = + page && !(await isWrapperAlias(outputDir, page)) + ? await basePages(outputDir, page, seen) + : [] + if (pages.length) { + return pages + } + return firstTypeArgument + ? basePagesOfType(outputDir, firstTypeArgument, seen) + : [] +} + +async function basePages( + outputDir: string, + from: string, + seen: Set, +): Promise> { + if (seen.has(from)) { + return [] + } + seen.add(from) + const page = await propertiesPage(outputDir, from) + if (page) { + return [page] + } + const code = (await readPage(outputDir, from))?.match( + /```ts\ntype \w+(?:<[^\n=]*>)? = ([\s\S]*?);\n```/, + )?.[1] + return code ? basePagesOfType(outputDir, code, seen) : [] +} + +// The base pages of the first type line that has any. +async function findBasePages(outputDir: string, typeLines: Array) { + for (const typeLine of typeLines) { + const type = typeLine + .replace(/\[`?(\w+)`?\]\([^)]*\)/g, '$1') + .replace(/[\\`]/g, '') + const pages = await basePagesOfType(outputDir, type, new Set()) + if (pages.length) { + return pages + } + } + return [] +} + +// The type line of each parameter and of the return value in one call signature. +function signatureTypes(signature: string) { + const parametersHeading = signature.match(/\n#{2,3} Parameters\n/) + const returnsHeading = signature.match(/\n#{2,3} Returns\n/) + const parameters = parametersHeading + ? signature.slice( + parametersHeading.index! + parametersHeading[0].length - 1, + returnsHeading?.index, + ) + : '' + // Only the headings one level below `Parameters`, not the properties of an inline object argument. + const parameterHeading = '#'.repeat( + (parametersHeading?.[0].trim().indexOf(' ') ?? 0) + 1, + ) + return { + parameters: new Map( + [ + ...parameters.matchAll( + new RegExp(`\\n${parameterHeading} (\\S+)\\n\\n([^\\n]*)`, 'g'), + ), + ].map(([, name, typeLine]) => [name!, typeLine!]), + ), + returns: returnsHeading + ? signature + .slice(returnsHeading.index! + returnsHeading[0].length) + .trim() + .split('\n')[0]! + : undefined, + } +} + +function readPage(outputDir: string, from: string) { + return readFile(resolve(outputDir, `${from}.md`), 'utf8').then( + (source) => source, + () => undefined, + ) +} + +// Resolves a type page to the interface pages it stands for: itself when it has a `## Properties` +// table, or the members of a plain alias or union. Anything else (intersections, `Omit`, `Override`, …) +// resolves to nothing, since no generated table describes it as-is. +async function resolveInterfacePages( + outputDir: string, + from: string, +): Promise | undefined> { + const source = await readPage(outputDir, from) + if (source === undefined) { + return undefined + } + if (source.includes('\n## Properties\n')) { + return [from] + } + const code = source.match( + /```ts\ntype \w+(?:<[^\n=]*>)? = ([\s\S]*?);\n```/, + )?.[1] + if (!code) { + return undefined + } + let members = code + while (/<[^<>]*>/.test(members)) { + members = members.replace(/<[^<>]*>/g, '') + } + const names = members + .split('|') + .map((member) => member.trim()) + .filter(Boolean) + if (!names.every((name) => /^\w+$/.test(name))) { + return undefined + } + const pages: Array = [] + for (const name of names) { + const resolved = + (await resolveInterfacePages(outputDir, `interfaces/${name}`)) ?? + (await resolveInterfacePages(outputDir, `type-aliases/${name}`)) + if (!resolved) { + return undefined + } + pages.push(...resolved) + } + return pages +} + +// The page whose `## Properties` table describes the type: the type itself, or the interface every +// member of a union extends. +async function propertiesPage(outputDir: string, from: string) { + const pages = await resolveInterfacePages(outputDir, from) + if (!pages?.length) { + return undefined + } + if (pages.length === 1) { + return pages[0] + } + const bases = new Set() + for (const page of pages) { + const base = (await readPage(outputDir, page))?.match( + /\n## Extends\n\n- \[`\w+`\]\((\w+)\.md\)[^\n]*\n\n##/, + )?.[1] + if (!base) { + return undefined + } + bases.add(`${dirname(page)}/${base}`) + } + return bases.size === 1 ? [...bases][0] : undefined +} + +async function readPropertiesTable(outputDir: string, from: string) { + const source = await readPage(outputDir, from) + const start = source?.indexOf('\n## Properties\n') ?? -1 + if (source === undefined || start === -1) { + return undefined + } + const fromDir = dirname(from) + return source + .slice(start + '\n## Properties\n'.length) + .trim() + .replace( + /\]\((?!https?:|#)([^)]+)\)/g, + (_, link: string) => + `](../${link.startsWith('../') ? link.slice(3) : `${fromDir}/${link}`})`, + ) +} + +// Adds to every function page without changing what TypeDoc generated: the properties of each +// argument and of the result, and an `## Overview` of every call signature on overloaded pages. The +// properties come from the generated page of the type, following plain aliases and, for a union, +// the interface all of its members extend. Types that override or omit properties get no table. +async function addReferenceDetails(outputDir: string) { + const files = await readdir(resolve(outputDir, 'functions')).catch( + () => [] as Array, + ) + for (const file of files.filter((name) => name.endsWith('.md'))) { + const pagePath = `functions/${file.slice(0, -3)}` + const pageFile = resolve(outputDir, `${pagePath}.md`) + const page = await readFile(pageFile, 'utf8') + const [head, ...signatures] = page.split('\n## Call Signature\n') + const isOverloaded = signatures.length > 1 + const lastSignature = signatures.at(-1) ?? page + + // Property tables of the arguments whose type has a `## Properties` table, and of the result. + const tables: Array<{ + id: string + title: string + table: string + parameter?: string + }> = [] + const parametersHeading = lastSignature.match(/\n#{2,3} Parameters\n/) + const returnsHeading = lastSignature.match(/\n#{2,3} Returns\n/) + const parameters = parametersHeading + ? lastSignature.slice( + parametersHeading.index! + parametersHeading[0].length - 1, + returnsHeading?.index, + ) + : '' + // Overloads describe the same arguments with different types, so a table missing from the + // last (most general) signature is taken from the latest earlier one that has it. + const signatureTypeLines = (signatures.length ? signatures : [page]) + .map(signatureTypes) + .reverse() + for (const name of signatureTypeLines[0]!.parameters.keys()) { + const table = await findPropertiesTable( + outputDir, + signatureTypeLines.flatMap((types) => types.parameters.get(name) ?? []), + ) + if (!table) { + continue + } + const argument = name.replace(/\\/g, '').replace(/\?$/, '') + const key = argument === '__namedParameters' ? 'props' : argument + tables.push({ + id: `${key}-properties`, + title: `\`${key}\` properties`, + table, + parameter: name, + }) + } + const resultTable = await findPropertiesTable( + outputDir, + signatureTypeLines.flatMap((types) => types.returns ?? []), + ) + if (resultTable) { + tables.push({ + id: 'result-properties', + title: 'Result properties', + table: resultTable, + }) + } + + // Property anchors are prefixed with the table's name, so they stay unique when two tables on + // the same page list the same properties. + const section = ( + level: number, + { id, title, table }: (typeof tables)[number], + ) => + `\n\n${'#'.repeat(level)} ${title}\n\n${table.replace( + /<\/a>/g, + ``, + )}` + + if (!isOverloaded) { + // Put each table at the end of the section it describes, so nothing is repeated. + let updated = page.trimEnd() + for (const entry of tables) { + const heading = entry.parameter + ? `\n### ${entry.parameter}\n` + : '\n## Returns\n' + const level = entry.parameter ? 3 : 2 + const start = updated.indexOf(heading) + if (start === -1) { + continue + } + const next = updated + .slice(start + heading.length) + .search(new RegExp(`\\n#{1,${level}} `)) + const insertAt = + next === -1 ? updated.length : start + heading.length + next + updated = `${updated.slice(0, insertAt).trimEnd()}\n\n${section(level + 1, entry)}\n${updated.slice(insertAt)}` + } + await writeFile(pageFile, `${updated.trimEnd()}\n`) + continue + } + + const entries = await Promise.all( + signatures.map(async (signature, index) => { + const code = signature.match(/```ts\n([\s\S]*?)\n```/)?.[1] ?? '' + const summary = signature + .split('\n### ')[0]! + .split('\n\n') + .map((block) => block.trim()) + .find( + (block) => + block !== '' && + !block.startsWith('```') && + !block.startsWith('Defined in:'), + ) + const label = ( + await Promise.all( + [ + code.match(/\((?:\w+\??): ([\s\S]*)/)?.[1], + code.match(/\): ([\s\S]*)/)?.[1], + ].map((type) => type && typeNameInCode(outputDir, type)), + ) + ) + .filter(Boolean) + .map((type) => `\`${type}\``) + .join(' → ') + return { + code, + line: `- [${label || `Call signature ${index + 1}`}](#call-signature-${index + 1})${summary ? `: ${summary.replace(/\n/g, ' ')}` : ''}`, + } + }), + ) + // Repeat the last (most general) signature's `Parameters` and `Returns` once at the end, one + // heading level up, with the property tables, so every argument and the result are listed together. + const promote = (block: string) => block.replace(/^#(#+) /gm, '$1 ') + let parametersSummary = parametersHeading + ? `## Parameters\n\n${promote(parameters.trim())}` + : '' + for (const entry of tables.filter((table) => table.parameter)) { + const heading = `\n### ${entry.parameter}\n` + const start = parametersSummary.indexOf(heading) + const next = parametersSummary + .slice(start + heading.length) + .search(/\n#{1,3} /) + const insertAt = + next === -1 ? parametersSummary.length : start + heading.length + next + parametersSummary = `${parametersSummary.slice(0, insertAt).trimEnd()}\n\n${section(4, entry)}\n${parametersSummary.slice(insertAt)}` + } + const returnsBlock = returnsHeading + ? lastSignature + .slice(returnsHeading.index! + returnsHeading[0].length) + .split(/\n#{2,3} /)[0]! + .trim() + : '' + const resultEntry = tables.find((table) => !table.parameter) + const summaries = [ + parametersSummary + ? `\n\n${parametersSummary.trimEnd()}` + : '', + returnsBlock + ? [ + '', + '', + '## Returns', + '', + returnsBlock, + ...(resultEntry ? ['', section(3, resultEntry)] : []), + ].join('\n') + : '', + ].filter(Boolean) + const links = [ + ...(parametersSummary ? ['[Parameters](#parameters-summary)'] : []), + ...(returnsBlock ? ['[Returns](#returns-summary)'] : []), + ] + const overview = [ + '## Overview', + '', + '```ts', + ...entries.map((entry) => entry.code), + '```', + '', + ...entries.map((entry) => entry.line), + ...(links.length > 0 ? ['', `See also: ${links.join(' · ')}`] : []), + ].join('\n') + const body = signatures + .map( + (signature, index) => + `\n\n\n## Call Signature\n${signature}`, + ) + .join('') + .trimEnd() + const appended = summaries.join('\n\n') + await writeFile( + pageFile, + `${head!.trimEnd()}\n\n${overview}\n${body}${appended ? `\n\n${appended}` : ''}\n`, + ) + } } const packages: Array = [