diff --git a/docs/framework/angular/reference/functions/dehydrate.md b/docs/framework/angular/reference/functions/dehydrate.md index 201200efdf..2c4abfc775 100644 --- a/docs/framework/angular/reference/functions/dehydrate.md +++ b/docs/framework/angular/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/angular/reference/functions/hydrate.md b/docs/framework/angular/reference/functions/hydrate.md index 435603b3af..65d204a296 100644 --- a/docs/framework/angular/reference/functions/hydrate.md +++ b/docs/framework/angular/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 38986e086e..5e781810da 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 { [injectInfiniteQuery](injectInfiniteQuery.md) to run an infinite query with these options. + + ## Call Signature ```ts @@ -283,3 +303,26 @@ export class Comments { ### See [injectInfiniteQuery](injectInfiniteQuery.md) to run an infinite query with these options. + + + +## 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 39aecc1d17..c6170378a9 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 ce629a0cf3..c84d3c9b5f 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 409d7c1653..a179eb3385 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 2a31bca1e7..262ab473b7 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 2e43406cfe..2ba5ceb4e2 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 bf715335bf..3f0da59d1a 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/angular/reference/functions/matchMutation.md +++ b/docs/framework/angular/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/angular/reference/functions/matchQuery.md +++ b/docs/framework/angular/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 fd29abb7ac..45ee3ff00f 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 01fb409f4e..12d0e1a36b 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 ac98f4c34f..f43652084f 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 | +| ------ | ------ | +| `ɵkind` | `TFeatureKind` | +| `ɵproviders` | `Provider`[] | diff --git a/docs/framework/angular/reference/functions/queryOptions.md b/docs/framework/angular/reference/functions/queryOptions.md index 46df24c42d..101fda4958 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 1e4f0a6473..702782bb52 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 8283b194c5..ee92ffcf55 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 19b833d42f..62cd230733 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 5758437708..22483547cd 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 201200efdf..2c4abfc775 100644 --- a/docs/framework/lit/reference/functions/dehydrate.md +++ b/docs/framework/lit/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/lit/reference/functions/hydrate.md b/docs/framework/lit/reference/functions/hydrate.md index a8bbe36ede..28aef5f832 100644 --- a/docs/framework/lit/reference/functions/hydrate.md +++ b/docs/framework/lit/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 a7f93674f4..d8df320e21 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/lit/reference/functions/matchMutation.md +++ b/docs/framework/lit/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/lit/reference/functions/matchQuery.md +++ b/docs/framework/lit/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 8bf7ba068e..21e1ec7d62 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 01fb409f4e..12d0e1a36b 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 809b86e7bd..0175f71d54 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 e8843de602..8e5445f982 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 16df7287a7..a2a1660e2e 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 c62bbb8d19..c3d23fff94 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 1757643329..97d22becfe 100644 --- a/docs/framework/preact/reference/functions/HydrationBoundary.md +++ b/docs/framework/preact/reference/functions/HydrationBoundary.md @@ -21,6 +21,17 @@ Note: Only `queries` can be dehydrated with an `HydrationBoundary`. [`HydrationBoundaryProps`](../interfaces/HydrationBoundaryProps.md) + + +#### `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 a8c7a117a6..ed408e1a82 100644 --- a/docs/framework/preact/reference/functions/QueryClientProvider.md +++ b/docs/framework/preact/reference/functions/QueryClientProvider.md @@ -20,6 +20,15 @@ comes back online). [`QueryClientProviderProps`](../type-aliases/QueryClientProviderProps.md) + + +#### `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 d742197141..a9d73f276b 100644 --- a/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md +++ b/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md @@ -19,6 +19,14 @@ reset any query errors within the boundaries of the component. [`QueryErrorResetBoundaryProps`](../interfaces/QueryErrorResetBoundaryProps.md) + + +#### `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 201200efdf..2c4abfc775 100644 --- a/docs/framework/preact/reference/functions/dehydrate.md +++ b/docs/framework/preact/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/preact/reference/functions/hydrate.md b/docs/framework/preact/reference/functions/hydrate.md index 435603b3af..65d204a296 100644 --- a/docs/framework/preact/reference/functions/hydrate.md +++ b/docs/framework/preact/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 1a8e0ea3a3..d58791e91f 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 }) { [useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + + ## Call Signature ```ts @@ -254,3 +274,25 @@ function Comments({ postId }: { postId: string }) { ### See [useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + + + +## 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/preact/reference/functions/matchMutation.md +++ b/docs/framework/preact/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/preact/reference/functions/matchQuery.md +++ b/docs/framework/preact/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 4b856590ba..fe69aa228d 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 01fb409f4e..12d0e1a36b 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 666f9fd42f..9cd59850c9 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 9fe8de0119..5808a40527 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 5dd612f9f8..86276c6960 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 d7c44f067f..62ce832f2c 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 d45c7a1488..2edc608217 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. + ## See [mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look diff --git a/docs/framework/preact/reference/functions/usePrefetchQuery.md b/docs/framework/preact/reference/functions/usePrefetchQuery.md index 29d83a2f62..5dec79fbf0 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 5afc02f100..b12b59df58 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) +- [`UseQueryOptions` → `UseQueryResult`](#call-signature-3) + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -84,6 +100,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -185,6 +203,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -382,3 +402,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 cb697b7bdb..0f0cc5dc9d 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 c19d6bf748..a63d3ac516 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 2b919a92c0..b262be8e16 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 76a2b31e12..ccd5902c32 100644 --- a/docs/framework/react/reference/functions/HydrationBoundary.md +++ b/docs/framework/react/reference/functions/HydrationBoundary.md @@ -21,6 +21,17 @@ Note: Only `queries` can be dehydrated with an `HydrationBoundary`. [`HydrationBoundaryProps`](../interfaces/HydrationBoundaryProps.md) + + +#### `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 68d6e73f2e..aef10f67be 100644 --- a/docs/framework/react/reference/functions/QueryClientProvider.md +++ b/docs/framework/react/reference/functions/QueryClientProvider.md @@ -22,6 +22,15 @@ comes back online). [`QueryClientProviderProps`](../type-aliases/QueryClientProviderProps.md) + + +#### `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 d2f56cc873..701b7a6b02 100644 --- a/docs/framework/react/reference/functions/QueryErrorResetBoundary.md +++ b/docs/framework/react/reference/functions/QueryErrorResetBoundary.md @@ -21,6 +21,14 @@ reset any query errors within the boundaries of the component. [`QueryErrorResetBoundaryProps`](../interfaces/QueryErrorResetBoundaryProps.md) + + +#### `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 201200efdf..2c4abfc775 100644 --- a/docs/framework/react/reference/functions/dehydrate.md +++ b/docs/framework/react/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/react/reference/functions/hydrate.md b/docs/framework/react/reference/functions/hydrate.md index 435603b3af..65d204a296 100644 --- a/docs/framework/react/reference/functions/hydrate.md +++ b/docs/framework/react/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 e1d3e1208c..c54fd5f274 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 }) { [useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + + ## Call Signature ```ts @@ -256,3 +276,25 @@ function Comments({ postId }: { postId: string }) { ### See [useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options. + + + +## 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/react/reference/functions/matchMutation.md +++ b/docs/framework/react/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/react/reference/functions/matchQuery.md +++ b/docs/framework/react/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 28562060e8..5f25b4b760 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 01fb409f4e..12d0e1a36b 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 cce05c912b..ea8a43a2e7 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 d22795064c..d7541dd172 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 19843c9734..8930649d3e 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 e99bbbd003..04512f1503 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 febbbba063..fd915a3ee5 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. + ## See [mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look diff --git a/docs/framework/react/reference/functions/usePrefetchQuery.md b/docs/framework/react/reference/functions/usePrefetchQuery.md index 3e3246310e..9a23bacd3f 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 94a4b35d05..fea552110b 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) +- [`UseQueryOptions` → `UseQueryResult`](#call-signature-3) + +See also: [Parameters](#parameters-summary) · [Returns](#returns-summary) + + + ## Call Signature ```ts @@ -86,6 +102,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -187,6 +205,8 @@ function Posts() { } ``` + + ## Call Signature ```ts @@ -384,3 +404,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 41f9cf4237..5c4661bd01 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 ceee7bdf04..d159cb261b 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 40e5c4accd..f78d887149 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 586c522dd6..fca0e621e4 100644 --- a/docs/framework/solid/reference/functions/QueryClientProvider.md +++ b/docs/framework/solid/reference/functions/QueryClientProvider.md @@ -20,6 +20,15 @@ comes back online). [`QueryClientProviderProps`](../type-aliases/QueryClientProviderProps.md) + + +#### `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 782758a438..50a55efe0c 100644 --- a/docs/framework/solid/reference/functions/dehydrate.md +++ b/docs/framework/solid/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/solid/reference/functions/hydrate.md b/docs/framework/solid/reference/functions/hydrate.md index 926f21b445..6c746514b0 100644 --- a/docs/framework/solid/reference/functions/hydrate.md +++ b/docs/framework/solid/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 73cba2889f..54c3c0394f 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/solid/reference/functions/matchMutation.md +++ b/docs/framework/solid/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/solid/reference/functions/matchQuery.md +++ b/docs/framework/solid/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 f30b791ac0..286c0eb992 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 01fb409f4e..12d0e1a36b 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 c586f4d70b..1f97c01184 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 4cc42c0676..e065df5e6a 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 19a86c4d98..6a0d6d204a 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 fe04b02534..390e26b113 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 2b1eff9cef..da2105e5f0 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 54b8c202c5..45373e60f7 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 20ddcbff34..f50bdc70ed 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 c06221075c..28de135d1f 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 d6a503566f..89b5848149 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) + +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 @@ -349,3 +369,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 201200efdf..2c4abfc775 100644 --- a/docs/framework/svelte/reference/functions/dehydrate.md +++ b/docs/framework/svelte/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/svelte/reference/functions/hydrate.md b/docs/framework/svelte/reference/functions/hydrate.md index 435603b3af..65d204a296 100644 --- a/docs/framework/svelte/reference/functions/hydrate.md +++ b/docs/framework/svelte/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 cbe59c6cdb..8bcaa80695 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/svelte/reference/functions/matchMutation.md +++ b/docs/framework/svelte/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/svelte/reference/functions/matchQuery.md +++ b/docs/framework/svelte/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 d6d51f9441..4982bd27ca 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 01fb409f4e..12d0e1a36b 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 348f3676cc..ea20ec435c 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 9f54479fb6..5956793090 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 5d3bf0f8dd..0588d630b4 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 1e733178ba..77d7579ad5 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 4eb83ce595..85fb549945 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 | +| ------ | ------ | +| `filters?` | [`MutationFilters`](../interfaces/MutationFilters.md) | +| `select?` | (`mutation`: `TMutation`) => `TResult` | + ### queryClient? [`QueryClient`](../classes/QueryClient.md) diff --git a/docs/framework/vue/reference/functions/dehydrate.md b/docs/framework/vue/reference/functions/dehydrate.md index 782758a438..50a55efe0c 100644 --- a/docs/framework/vue/reference/functions/dehydrate.md +++ b/docs/framework/vue/reference/functions/dehydrate.md @@ -25,10 +25,30 @@ falling back to the client's `dehydrate` default options, and finally to `defaul [`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}` + + +#### `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) + + +### Result properties + +| Property | Type | +| ------ | ------ | +| `mutations` | `DehydratedMutation`[] | +| `queries` | `DehydratedQuery`[] | + ## Example ```ts diff --git a/docs/framework/vue/reference/functions/hydrate.md b/docs/framework/vue/reference/functions/hydrate.md index 926f21b445..6c746514b0 100644 --- a/docs/framework/vue/reference/functions/hydrate.md +++ b/docs/framework/vue/reference/functions/hydrate.md @@ -30,10 +30,27 @@ promise, it is resumed via `query.fetch()` (reusing that promise as `initialProm `Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\> + + +#### `dehydratedState` properties + +Built from [`DehydratedState`](../interfaces/DehydratedState.md#properties). See the type above for what it changes. + ### options? [`HydrateOptions`](../interfaces/HydrateOptions.md) + + +#### `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 7f2e6c71e2..92e8570389 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 0bc16b361f..7903e79a6b 100644 --- a/docs/framework/vue/reference/functions/matchMutation.md +++ b/docs/framework/vue/reference/functions/matchMutation.md @@ -19,6 +19,17 @@ If a `mutationKey` filter is provided but the mutation has no `mutationKey` of i [`MutationFilters`](../interfaces/MutationFilters.md) + + +#### `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 ce575fc2b6..961ff43c3d 100644 --- a/docs/framework/vue/reference/functions/matchQuery.md +++ b/docs/framework/vue/reference/functions/matchQuery.md @@ -18,6 +18,19 @@ Every filter that is specified must match; filters that are left unspecified are [`QueryFilters`](../interfaces/QueryFilters.md) + + +#### `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 7d1081744c..c32bd9a5dd 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 01fb409f4e..12d0e1a36b 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 af4ddcd4b0..a36324c239 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 486bdbca68..fb12de6fed 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 2e58f483d7..b72306f80e 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 2714eb2c52..2af0bb0593 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 b111f5b7e7..485bfe8d15 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 = [