diff --git a/docs/framework/preact/reference/functions/HydrationBoundary.md b/docs/framework/preact/reference/functions/HydrationBoundary.md index 3d48a51149..1a6e6bde46 100644 --- a/docs/framework/preact/reference/functions/HydrationBoundary.md +++ b/docs/framework/preact/reference/functions/HydrationBoundary.md @@ -7,7 +7,13 @@ title: HydrationBoundary function HydrationBoundary(__namedParameters): Element; ``` -Defined in: [preact-query/src/HydrationBoundary.tsx:26](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L26) +Defined in: [preact-query/src/HydrationBoundary.tsx:85](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L85) + +`HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by +`useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on +update timestamp. + +Note: Only `queries` can be dehydrated with an `HydrationBoundary`. ## Parameters @@ -18,3 +24,40 @@ Defined in: [preact-query/src/HydrationBoundary.tsx:26](https://github.com/TanSt ## Returns `Element` + +The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the +cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect +after commit. + +## Examples + +```tsx +import { HydrationBoundary } from '@tanstack/preact-query' + +function App() { + return ... +} +``` + +Server-side prefetch handed off to the client via `dehydrate`: +```tsx +import { noop } from '@tanstack/query-core' +import { HydrationBoundary, dehydrate } from '@tanstack/preact-query' + +async function ServerComponent() { + const queryClient = getQueryClient() + + await queryClient + .query({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + .catch(noop) + + return ( + + + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/QueryClientProvider.md b/docs/framework/preact/reference/functions/QueryClientProvider.md index 2ac3ccfbda..6283568f84 100644 --- a/docs/framework/preact/reference/functions/QueryClientProvider.md +++ b/docs/framework/preact/reference/functions/QueryClientProvider.md @@ -7,7 +7,9 @@ title: QueryClientProvider function QueryClientProvider(__namedParameters): VNode; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:29](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L29) +Defined in: [preact-query/src/QueryClientProvider.tsx:63](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L63) + +Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. ## Parameters @@ -18,3 +20,17 @@ Defined in: [preact-query/src/QueryClientProvider.tsx:29](https://github.com/Tan ## Returns `VNode` + +The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + +## Example + +```tsx +import { QueryClient, QueryClientProvider } from '@tanstack/preact-query' + +const queryClient = new QueryClient() + +function App() { + return ... +} +``` diff --git a/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md b/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md index aa06d5317d..77a8e44809 100644 --- a/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md +++ b/docs/framework/preact/reference/functions/QueryErrorResetBoundary.md @@ -7,7 +7,11 @@ title: QueryErrorResetBoundary function QueryErrorResetBoundary(__namedParameters): Element; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:48](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L48) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:154](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L154) + +When using **suspense** or **throwOnError** in your queries, you need a way to let queries know that you want to +try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can +reset any query errors within the boundaries of the component. ## Parameters @@ -18,3 +22,45 @@ Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:48](https://github.com ## Returns `Element` + +The `children`, rendered as-is, or called with the boundary's QueryErrorResetBoundaryValue +if `children` is a function. + +## Example + +```tsx +import { useErrorBoundary } from 'preact/hooks' +import type { ComponentChildren } from 'preact' +import { QueryErrorResetBoundary } from '@tanstack/preact-query' + +function ErrorBoundary({ + children, + reset, +}: { + children: ComponentChildren + reset: () => void +}) { + const [error, resetError] = useErrorBoundary(() => reset()) + + if (error) { + return ( +
+ There was an error! + +
+ ) + } + + return children +} + +const App = () => ( + + {({ reset }) => ( + + + + )} + +) +``` diff --git a/docs/framework/preact/reference/functions/infiniteQueryOptions.md b/docs/framework/preact/reference/functions/infiniteQueryOptions.md index a304f4271c..0a8fbcb07a 100644 --- a/docs/framework/preact/reference/functions/infiniteQueryOptions.md +++ b/docs/framework/preact/reference/functions/infiniteQueryOptions.md @@ -9,7 +9,13 @@ title: infiniteQueryOptions function infiniteQueryOptions(options): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; ``` -Defined in: [preact-query/src/infiniteQueryOptions.ts:76](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L76) +Defined in: [preact-query/src/infiniteQueryOptions.ts:122](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L122) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. + +This overload is selected when `initialData` is set. ### Type Parameters @@ -39,9 +45,30 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:76](https://github.com/Tan [`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 -[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `InfiniteData`\<`TQueryFnData`, `unknown`\>, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Example + +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + +export const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + initialData: { pages: [], pageParams: [] }, +}) + +function Projects() { + const { data } = useInfiniteQuery(projectsOptions) + return <>{data.pages.map((page) => page.projects.map((p) =>

{p.name}

))} +} +``` ## Call Signature @@ -49,7 +76,11 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:76](https://github.com/Tan function infiniteQueryOptions(options): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag, TError>; ``` -Defined in: [preact-query/src/infiniteQueryOptions.ts:99](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L99) +Defined in: [preact-query/src/infiniteQueryOptions.ts:194](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L194) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. ### Type Parameters @@ -79,9 +110,51 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:99](https://github.com/Tan [`UnusedSkipTokenInfiniteOptions`](../type-aliases/UnusedSkipTokenInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UnusedSkipTokenInfiniteOptions](../type-aliases/UnusedSkipTokenInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + ### Returns -`OmitKeyof`\<[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>, `"queryFn"`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `InfiniteData`\<`TQueryFnData`, `unknown`\>, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Examples + +```tsx +import { infiniteQueryOptions } from '@tanstack/preact-query' + +export const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) +``` + +A parameterized factory, reused across a hook and an imperative call with the same cache entry: +```tsx +import { noop } from '@tanstack/query-core' +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + +export const commentsOptions = (postId: string) => + infiniteQueryOptions({ + queryKey: ['post', postId, 'comments'], + queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + +function Comments({ postId }: { postId: string }) { + const result = useInfiniteQuery(commentsOptions(postId)) + if (!result.isSuccess) return 'Loading...' + return ( + <> + {result.data.pages.map((page) => page.comments.map((c) =>

{c.text}

))} + + ) +} + +// Elsewhere, e.g. to warm the cache before rendering ``: +queryClient.infiniteQuery(commentsOptions(postId)).catch(noop) +``` ## Call Signature @@ -89,7 +162,11 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:99](https://github.com/Tan function infiniteQueryOptions(options): UseInfiniteQueryOptions & object & QueryKeyWithDataTag, TError>; ``` -Defined in: [preact-query/src/infiniteQueryOptions.ts:122](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L122) +Defined in: [preact-query/src/infiniteQueryOptions.ts:266](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L266) + +You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. +These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. +`options.queryKey` is required and is the query key to generate options for. ### Type Parameters @@ -119,6 +196,48 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:122](https://github.com/Ta [`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + ### Returns -[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `InfiniteData`\<`TQueryFnData`, `unknown`\>, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Examples + +```tsx +import { infiniteQueryOptions } from '@tanstack/preact-query' + +export const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) +``` + +A parameterized factory, reused across a hook and an imperative call with the same cache entry: +```tsx +import { noop } from '@tanstack/query-core' +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + +export const commentsOptions = (postId: string) => + infiniteQueryOptions({ + queryKey: ['post', postId, 'comments'], + queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + +function Comments({ postId }: { postId: string }) { + const result = useInfiniteQuery(commentsOptions(postId)) + if (!result.isSuccess) return 'Loading...' + return ( + <> + {result.data.pages.map((page) => page.comments.map((c) =>

{c.text}

))} + + ) +} + +// Elsewhere, e.g. to warm the cache before rendering ``: +queryClient.infiniteQuery(commentsOptions(postId)).catch(noop) +``` diff --git a/docs/framework/preact/reference/functions/mutationOptions.md b/docs/framework/preact/reference/functions/mutationOptions.md index a72866cc0a..66212f8e10 100644 --- a/docs/framework/preact/reference/functions/mutationOptions.md +++ b/docs/framework/preact/reference/functions/mutationOptions.md @@ -9,7 +9,11 @@ title: mutationOptions function mutationOptions(options): WithRequired, "mutationKey">; ``` -Defined in: [preact-query/src/mutationOptions.ts:5](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L5) +Defined in: [preact-query/src/mutationOptions.ts:48](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L48) + +You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A +`mutationKey` is required on this overload so the mutation can be looked up later, e.g. with +`useMutationState`. ### Type Parameters @@ -35,17 +39,60 @@ Defined in: [preact-query/src/mutationOptions.ts:5](https://github.com/TanStack/ `WithRequired`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> +The mutation options to use, identical to what you'd pass to `useMutation`, with a +required `mutationKey`. + ### Returns `WithRequired`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> +The same options object, unchanged. + +### Examples + +```tsx +import { mutationOptions, useMutation } from '@tanstack/preact-query' + +export const createPostOptions = mutationOptions({ + mutationKey: ['posts', 'create'], + mutationFn: createPost, +}) + +function CreatePost() { + const mutation = useMutation(createPostOptions) + return +} +``` + +Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: +```tsx +import { mutationOptions, useMutationState } from '@tanstack/preact-query' + +const createPostOptions = mutationOptions({ + mutationKey: ['posts', 'create'], + mutationFn: createPost, +}) + +function SavingIndicator() { + const isCreatingPost = useMutationState({ + filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + }).length > 0 + + return isCreatingPost ? Saving… : null +} +``` + ## Call Signature ```ts function mutationOptions(options): Omit, "mutationKey">; ``` -Defined in: [preact-query/src/mutationOptions.ts:19](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L19) +Defined in: [preact-query/src/mutationOptions.ts:85](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L85) + +You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No +`mutationKey` is required on this overload — use this when you don't need to look the mutation up later +(e.g. with `useMutationState`). ### Type Parameters @@ -71,6 +118,26 @@ Defined in: [preact-query/src/mutationOptions.ts:19](https://github.com/TanStack `Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> +The mutation options to use, identical to what you'd pass to `useMutation`, without a +`mutationKey`. + ### Returns `Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\> + +The same options object, unchanged. + +### Example + +```tsx +import { mutationOptions, useMutation } from '@tanstack/preact-query' + +export const createPostOptions = mutationOptions({ + mutationFn: createPost, +}) + +function CreatePost() { + const mutation = useMutation(createPostOptions) + return +} +``` diff --git a/docs/framework/preact/reference/functions/queryOptions.md b/docs/framework/preact/reference/functions/queryOptions.md index 4db0bb8237..c8844b2ed1 100644 --- a/docs/framework/preact/reference/functions/queryOptions.md +++ b/docs/framework/preact/reference/functions/queryOptions.md @@ -9,7 +9,13 @@ title: queryOptions function queryOptions(options): Omit, "queryFn"> & object & QueryKeyWithDataTag; ``` -Defined in: [preact-query/src/queryOptions.ts:53](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L53) +Defined in: [preact-query/src/queryOptions.ts:103](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L103) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. + +This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. ### Type Parameters @@ -35,9 +41,29 @@ Defined in: [preact-query/src/queryOptions.ts:53](https://github.com/TanStack/qu [`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`, with `initialData` set. + ### Returns -`Omit`\<[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>, `"queryFn"`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `TQueryFnData`, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Example + +```tsx +import { queryOptions, useQuery } from '@tanstack/preact-query' + +export const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, + initialData: [], +}) + +function Posts() { + // `data` is `Post[]`, never `undefined`, thanks to `initialData`. + const { data } = useQuery(postsOptions) + return <>{data.map((post) =>

{post.title}

)} +} +``` ## Call Signature @@ -45,7 +71,11 @@ Defined in: [preact-query/src/queryOptions.ts:53](https://github.com/TanStack/qu function queryOptions(options): OmitKeyof, "queryFn"> & object & QueryKeyWithDataTag; ``` -Defined in: [preact-query/src/queryOptions.ts:63](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L63) +Defined in: [preact-query/src/queryOptions.ts:169](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L169) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. ### Type Parameters @@ -71,9 +101,58 @@ Defined in: [preact-query/src/queryOptions.ts:63](https://github.com/TanStack/qu [`UnusedSkipTokenOptions`](../type-aliases/UnusedSkipTokenOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [UnusedSkipTokenOptions](../type-aliases/UnusedSkipTokenOptions.md) to use — everything you can pass to `useQuery`. + ### Returns -`OmitKeyof`\<[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>, `"queryFn"`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `TQueryFnData`, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Examples + +```tsx +import { queryOptions } from '@tanstack/preact-query' + +export const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, +}) +``` + +A parameterized factory, reused across a hook and an imperative call with the same cache entry: +```tsx +import { noop } from '@tanstack/query-core' +import { queryOptions, useQuery } from '@tanstack/preact-query' + +export const postOptions = (id: string) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function Post({ id }: { id: string }) { + const { data } = useQuery(postOptions(id)) + return

{data?.title}

+} + +// Elsewhere, e.g. to warm the cache before rendering ``: +queryClient.query(postOptions(id)).catch(noop) +``` + +The same options object works with every API that accepts query options: +```tsx +import { noop } from '@tanstack/query-core' +import { queryOptions, useQuery, useSuspenseQuery } from '@tanstack/preact-query' + +const todosOptions = queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodos, +}) + +useQuery(todosOptions) +useSuspenseQuery(todosOptions) +queryClient.query(todosOptions).catch(noop) +queryClient.getQueryData(todosOptions.queryKey) // typed as Array | undefined +``` ## Call Signature @@ -81,7 +160,11 @@ Defined in: [preact-query/src/queryOptions.ts:63](https://github.com/TanStack/qu function queryOptions(options): UseQueryOptions & object & QueryKeyWithDataTag; ``` -Defined in: [preact-query/src/queryOptions.ts:73](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L73) +Defined in: [preact-query/src/queryOptions.ts:235](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L235) + +You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can +be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and +is the query key to generate options for. ### Type Parameters @@ -107,6 +190,55 @@ Defined in: [preact-query/src/queryOptions.ts:73](https://github.com/TanStack/qu [`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`. + ### Returns -[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` & `QueryKeyWithDataTag`\<`TQueryKey`, `TQueryFnData`, `TError`\> +The same options object, typed so that `queryKey` carries the inferred data type. + +### Examples + +```tsx +import { queryOptions } from '@tanstack/preact-query' + +export const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, +}) +``` + +A parameterized factory, reused across a hook and an imperative call with the same cache entry: +```tsx +import { noop } from '@tanstack/query-core' +import { queryOptions, useQuery } from '@tanstack/preact-query' + +export const postOptions = (id: string) => + queryOptions({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + }) + +function Post({ id }: { id: string }) { + const { data } = useQuery(postOptions(id)) + return

{data?.title}

+} + +// Elsewhere, e.g. to warm the cache before rendering ``: +queryClient.query(postOptions(id)).catch(noop) +``` + +The same options object works with every API that accepts query options: +```tsx +import { noop } from '@tanstack/query-core' +import { queryOptions, useQuery, useSuspenseQuery } from '@tanstack/preact-query' + +const todosOptions = queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodos, +}) + +useQuery(todosOptions) +useSuspenseQuery(todosOptions) +queryClient.query(todosOptions).catch(noop) +queryClient.getQueryData(todosOptions.queryKey) // typed as Array | undefined +``` diff --git a/docs/framework/preact/reference/functions/useInfiniteQuery.md b/docs/framework/preact/reference/functions/useInfiniteQuery.md index 87fa3c3fa5..ebc08137b7 100644 --- a/docs/framework/preact/reference/functions/useInfiniteQuery.md +++ b/docs/framework/preact/reference/functions/useInfiniteQuery.md @@ -9,7 +9,12 @@ title: useInfiniteQuery function useInfiniteQuery(options, queryClient?): DefinedUseInfiniteQueryResult; ``` -Defined in: [preact-query/src/useInfiniteQuery.ts:21](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L21) +Defined in: [preact-query/src/useInfiniteQuery.ts:51](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L51) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +This overload is selected when `initialData` is set. ### Type Parameters @@ -39,21 +44,51 @@ Defined in: [preact-query/src/useInfiniteQuery.ts:21](https://github.com/TanStac [`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`, with `initialData` set. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\> +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Example + +```tsx +import { useInfiniteQuery } from '@tanstack/preact-query' + +function Projects() { + const { data } = useInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + initialData: { pages: [], pageParams: [] }, + }) + + return <>{data.pages.map((page) => page.projects.map((p) =>

{p.name}

))} +} +``` + ## Call Signature ```ts function useInfiniteQuery(options, queryClient?): UseInfiniteQueryResult; ``` -Defined in: [preact-query/src/useInfiniteQuery.ts:38](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L38) +Defined in: [preact-query/src/useInfiniteQuery.ts:105](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L105) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. ### Type Parameters @@ -83,21 +118,64 @@ Defined in: [preact-query/src/useInfiniteQuery.ts:38](https://github.com/TanStac [`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\> +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Example + +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + +const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) + +function Projects() { + const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = + useInfiniteQuery(projectsOptions) + + return ( + + ) +} +``` + ## Call Signature ```ts function useInfiniteQuery(options, queryClient?): UseInfiniteQueryResult; ``` -Defined in: [preact-query/src/useInfiniteQuery.ts:55](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L55) +Defined in: [preact-query/src/useInfiniteQuery.ts:163](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L163) + +The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, +`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + +Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch +behavior, resulting in outdated data. Make sure to call these functions only in response to user actions, +or add conditions like `hasNextPage && !isFetching`. ### Type Parameters @@ -127,10 +205,46 @@ Defined in: [preact-query/src/useInfiniteQuery.ts:55](https://github.com/TanStac [`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use — everything you can pass to `useInfiniteQuery`. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, +`fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and +`isFetchingPreviousPage`. + +### Example + +```tsx +import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + +const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) + +function Projects() { + const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = + useInfiniteQuery(projectsOptions) + + return ( + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/useIsFetching.md b/docs/framework/preact/reference/functions/useIsFetching.md index 2e8d489d81..d31f330b99 100644 --- a/docs/framework/preact/reference/functions/useIsFetching.md +++ b/docs/framework/preact/reference/functions/useIsFetching.md @@ -7,7 +7,10 @@ title: useIsFetching function useIsFetching(filters?, queryClient?): number; ``` -Defined in: [preact-query/src/useIsFetching.ts:8](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useIsFetching.ts#L8) +Defined in: [preact-query/src/useIsFetching.ts:28](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useIsFetching.ts#L28) + +`useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or +fetching in the background (useful for app-wide loading indicators). ## Parameters @@ -15,10 +18,29 @@ Defined in: [preact-query/src/useIsFetching.ts:8](https://github.com/TanStack/qu `QueryFilters`\ +The QueryFilters to narrow down the matched queries. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `number` + +Will be the `number` of the queries that your application is currently loading or fetching in the +background. + +## Example + +```tsx +import { useIsFetching } from '@tanstack/preact-query' + +// How many queries are fetching? +const isFetching = useIsFetching() +// How many queries matching the posts prefix are fetching? +const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) +``` diff --git a/docs/framework/preact/reference/functions/useIsMutating.md b/docs/framework/preact/reference/functions/useIsMutating.md index 13327fc0ca..fc3b0ad613 100644 --- a/docs/framework/preact/reference/functions/useIsMutating.md +++ b/docs/framework/preact/reference/functions/useIsMutating.md @@ -7,7 +7,10 @@ title: useIsMutating function useIsMutating(filters?, queryClient?): number; ``` -Defined in: [preact-query/src/useMutationState.ts:14](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L14) +Defined in: [preact-query/src/useMutationState.ts:33](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L33) + +`useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching +(useful for app-wide loading indicators). ## Parameters @@ -15,10 +18,28 @@ Defined in: [preact-query/src/useMutationState.ts:14](https://github.com/TanStac `MutationFilters`\<`unknown`, `Error`, `unknown`, `unknown`\> +The MutationFilters to narrow down the matched mutations. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `number` + +Will be the `number` of the mutations that your application is currently fetching. + +## Example + +```tsx +import { useIsMutating } from '@tanstack/preact-query' + +// How many mutations are fetching? +const isMutating = useIsMutating() +// How many mutations matching the posts prefix are fetching? +const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) +``` diff --git a/docs/framework/preact/reference/functions/useIsRestoring.md b/docs/framework/preact/reference/functions/useIsRestoring.md index 5b3b14ecd7..e81909e222 100644 --- a/docs/framework/preact/reference/functions/useIsRestoring.md +++ b/docs/framework/preact/reference/functions/useIsRestoring.md @@ -7,8 +7,14 @@ title: useIsRestoring function useIsRestoring(): boolean; ``` -Defined in: [preact-query/src/IsRestoringProvider.ts:6](https://github.com/TanStack/query/blob/main/packages/preact-query/src/IsRestoringProvider.ts#L6) +Defined in: [preact-query/src/IsRestoringProvider.ts:13](https://github.com/TanStack/query/blob/main/packages/preact-query/src/IsRestoringProvider.ts#L13) + +If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to +check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid +race conditions between the restore and mounting queries. ## Returns `boolean` + +`true` while a persisted client is being restored, `false` otherwise. diff --git a/docs/framework/preact/reference/functions/useMutation.md b/docs/framework/preact/reference/functions/useMutation.md index 0a67753e61..a04d9c9328 100644 --- a/docs/framework/preact/reference/functions/useMutation.md +++ b/docs/framework/preact/reference/functions/useMutation.md @@ -7,7 +7,10 @@ title: useMutation function useMutation(options, queryClient?): UseMutationResult; ``` -Defined in: [preact-query/src/useMutation.ts:20](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutation.ts#L20) +Defined in: [preact-query/src/useMutation.ts:86](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutation.ts#L86) + +Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. +`useMutation` is the hook for that. ## Type Parameters @@ -33,10 +36,74 @@ Defined in: [preact-query/src/useMutation.ts:20](https://github.com/TanStack/que [`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> +The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use — everything you can pass to `useMutation`. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns [`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\> + +`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second +argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared +mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've +made. + +## Examples + +```tsx +import { useMutation, useQueryClient } from '@tanstack/preact-query' + +function AddTodo() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + }) + + return ( + + ) +} +``` + +Optimistic update via `onMutate`, rolling back on `onError`: +```tsx +import { useMutation, useQueryClient } from '@tanstack/preact-query' + +function AddTodo() { + const queryClient = useQueryClient() + + const addMutation = useMutation({ + mutationFn: addTodo, + onMutate: async (newTodo) => { + await queryClient.cancelQueries({ queryKey: ['todos'] }) + const previousTodos = queryClient.getQueryData>(['todos']) + + queryClient.setQueryData>(['todos'], (old) => [ + ...(old ?? []), + newTodo, + ]) + + // Passed to `onError` as `context` if the mutation fails. + return { previousTodos } + }, + onError: (_err, _newTodo, context) => { + queryClient.setQueryData(['todos'], context?.previousTodos) + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, + }) + + return ( + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/useMutationState.md b/docs/framework/preact/reference/functions/useMutationState.md index 28b6bda79c..85f58a1ab7 100644 --- a/docs/framework/preact/reference/functions/useMutationState.md +++ b/docs/framework/preact/reference/functions/useMutationState.md @@ -7,7 +7,11 @@ title: useMutationState function useMutationState(options, queryClient?): TResult[]; ``` -Defined in: [preact-query/src/useMutationState.ts:63](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L63) +Defined in: [preact-query/src/useMutationState.ts:137](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L137) + +`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass +`filters` (MutationFilters) to narrow down your mutations, and `select` to transform the mutation +state. ## Type Parameters @@ -25,10 +29,61 @@ Defined in: [preact-query/src/useMutationState.ts:63](https://github.com/TanStac `MutationStateOptions`\<`TResult`, `TMutation`\> = `{}` +The `filters` to narrow down matched mutations, and an optional `select` to transform the +mutation state. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `TResult`[] + +Will be an Array of whatever `select` returns for each matching mutation. + +## Examples + +Get all variables of all running mutations: +```tsx +import { useMutationState } from '@tanstack/preact-query' + +const variables = useMutationState({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, +}) +``` + +Get all data for specific mutations via the `mutationKey`: +```tsx +import { useMutation, useMutationState } from '@tanstack/preact-query' + +const mutationKey = ['posts'] + +// Some mutation that we want to get the state for +const mutation = useMutation({ + mutationKey, + mutationFn: createPosts, +}) + +const data = useMutationState({ + // this mutation key needs to match the mutation key of the given mutation (see above) + filters: { mutationKey }, + select: (mutation) => mutation.state.data, +}) +``` + +Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the +mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the +latest invocation: +```tsx +const data = useMutationState({ + filters: { mutationKey: ['posts'] }, + select: (mutation) => mutation.state.data, +}) + +const latest = data[data.length - 1] +``` diff --git a/docs/framework/preact/reference/functions/usePrefetchInfiniteQuery.md b/docs/framework/preact/reference/functions/usePrefetchInfiniteQuery.md index 33b0cb9300..465bb7c5f1 100644 --- a/docs/framework/preact/reference/functions/usePrefetchInfiniteQuery.md +++ b/docs/framework/preact/reference/functions/usePrefetchInfiniteQuery.md @@ -7,7 +7,17 @@ title: usePrefetchInfiniteQuery function usePrefetchInfiniteQuery(options, queryClient?): void; ``` -Defined in: [preact-query/src/usePrefetchInfiniteQuery.tsx:7](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchInfiniteQuery.tsx#L7) +Defined in: [preact-query/src/usePrefetchInfiniteQuery.tsx:47](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchInfiniteQuery.tsx#L47) + +`usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, +before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass +everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though +`queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless +a default query function has been defined. + +`getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, +as well as pageParam information, and should return a single variable that will be passed to your query +function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. ## Type Parameters @@ -37,10 +47,42 @@ Defined in: [preact-query/src/usePrefetchInfiniteQuery.tsx:7](https://github.com [`UsePrefetchInfiniteQueryOptions`](../type-aliases/UsePrefetchInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UsePrefetchInfiniteQueryOptions](../type-aliases/UsePrefetchInfiniteQueryOptions.md) to use — everything you can pass to `queryClient.infiniteQuery`. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `void` + +`void` — nothing is returned. + +## Example + +```tsx +import { Suspense } from 'preact/compat' +import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/preact-query' + +const projectsOptions = infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, +}) + +function App() { + // Fire the prefetch during render, before the suspense boundary below. + usePrefetchInfiniteQuery(projectsOptions) + + return ( + Loading projects...}> + + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/usePrefetchQuery.md b/docs/framework/preact/reference/functions/usePrefetchQuery.md index 8f9648d84a..c935d40599 100644 --- a/docs/framework/preact/reference/functions/usePrefetchQuery.md +++ b/docs/framework/preact/reference/functions/usePrefetchQuery.md @@ -7,7 +7,12 @@ title: usePrefetchQuery function usePrefetchQuery(options, queryClient?): void; ``` -Defined in: [preact-query/src/usePrefetchQuery.tsx:7](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchQuery.tsx#L7) +Defined in: [preact-query/src/usePrefetchQuery.tsx:38](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchQuery.tsx#L38) + +`usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before +a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to +`usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and +`queryFn` is required unless a default query function has been defined. ## Type Parameters @@ -37,10 +42,38 @@ Defined in: [preact-query/src/usePrefetchQuery.tsx:7](https://github.com/TanStac [`UsePrefetchQueryOptions`](../type-aliases/UsePrefetchQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\> +The [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `void` + +`void` — nothing is returned. + +## Example + +```tsx +import { Suspense } from 'preact/compat' +import { usePrefetchQuery } from '@tanstack/preact-query' + +function App() { + // Fire the prefetch during render, before the suspense boundary below. + usePrefetchQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + return ( + Loading posts...}> + + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/useQueries.md b/docs/framework/preact/reference/functions/useQueries.md index 382fc00865..aa7a776087 100644 --- a/docs/framework/preact/reference/functions/useQueries.md +++ b/docs/framework/preact/reference/functions/useQueries.md @@ -7,7 +7,19 @@ title: useQueries function useQueries(__namedParameters, queryClient?): TCombinedResult; ``` -Defined in: [preact-query/src/useQueries.ts:207](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQueries.ts#L207) +Defined in: [preact-query/src/useQueries.ts:257](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQueries.ts#L257) + +The `useQueries` hook can be used to fetch a variable number of queries. + +The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the +`queryClient` option - because the `QueryClient` can be passed in on the top level). + +Having the same query key more than once in the array of query objects may cause some data to be shared +between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired +structure. + +The `combine` option can be used to combine the results of the queries into a single value. The result will +be structurally shared to be as referentially stable as possible. ## Type Parameters @@ -27,19 +39,67 @@ Defined in: [preact-query/src/useQueries.ts:207](https://github.com/TanStack/que (`result`) => `TCombinedResult` +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + #### queries \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>, `GetUseQueryOptionsForUseQueries`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : readonly ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : readonly `unknown`[] *extends* `T` ? `T` : `T` *extends* `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : `UseQueryOptionsForUseQueries`\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\] \| readonly \[\{ \[K in string \| number \| symbol\]: GetUseQueryOptionsForUseQueries\\]\> \}\] +An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and +`subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and +`placeholderData` accepts a QueriesPlaceholderDataFunction, which is called with `previousData` +and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + #### subscribed? `boolean` +Set this to `false` to unsubscribe this observer from updates to the query cache. Defaults to `true`. + ### queryClient? `QueryClient` +Use this to provide a custom QueryClient. Otherwise, the one from the nearest context +will be used. + ## Returns `TCombinedResult` + +The combined result. Without `combine`, this is an array with all the query results, in the same +order as the input. When `combine` is provided, this is the value returned by `combine` instead. + +## Examples + +```tsx +import { useQueries } from '@tanstack/preact-query' + +const ids = [1, 2, 3] +const results = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + staleTime: Infinity, + })), +}) +``` + +Combining results into a single value: +```tsx +const ids = [1, 2, 3] +const combinedQueries = useQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + combine: (results) => { + return { + data: results.map((result) => result.data), + pending: results.some((result) => result.isPending), + } + }, +}) +``` diff --git a/docs/framework/preact/reference/functions/useQuery.md b/docs/framework/preact/reference/functions/useQuery.md index ff2b38d7be..307464f120 100644 --- a/docs/framework/preact/reference/functions/useQuery.md +++ b/docs/framework/preact/reference/functions/useQuery.md @@ -9,7 +9,9 @@ title: useQuery function useQuery(options, queryClient?): DefinedUseQueryResult; ``` -Defined in: [preact-query/src/useQuery.ts:15](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L15) +Defined in: [preact-query/src/useQuery.ts:41](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L41) + +This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. ### Type Parameters @@ -35,21 +37,47 @@ Defined in: [preact-query/src/useQuery.ts:15](https://github.com/TanStack/query/ [`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`, with `initialData` set. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\> +The current query result, typed so that `status` is `success` — or `error` if a fetch attempt +fails while keeping the existing data (`status` never resolves to `pending` in this overload's type, +since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience. + +### Example + +```tsx +import { useQuery } from '@tanstack/preact-query' + +function Posts() { + // `data` is `Post[]`, never `undefined`, thanks to `initialData`. + const { data } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + initialData: [], + }) + + return <>{data.map((post) =>

{post.title}

)} +} +``` + ## Call Signature ```ts function useQuery(options, queryClient?): UseQueryResult; ``` -Defined in: [preact-query/src/useQuery.ts:25](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L25) +Defined in: [preact-query/src/useQuery.ts:85](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L85) ### Type Parameters @@ -75,21 +103,57 @@ Defined in: [preact-query/src/useQuery.ts:25](https://github.com/TanStack/query/ [`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `useQuery`. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\> +The current query result. `status` is `pending` if there is no cached data and no query attempt +has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to +display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience. + +### Example + +```tsx +import { queryOptions, useQuery } from '@tanstack/preact-query' + +const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, +}) + +function Posts() { + const { status, data, error, isFetching } = useQuery(postsOptions) + + if (status === 'pending') return 'Loading...' + if (status === 'error') return Error: {error.message} + + return ( +
+ {data.map((post) => ( +

{post.title}

+ ))} +
{isFetching ? 'Background Updating...' : ' '}
+
+ ) +} +``` + ## Call Signature ```ts function useQuery(options, queryClient?): UseQueryResult; ``` -Defined in: [preact-query/src/useQuery.ts:35](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L35) +Defined in: [preact-query/src/useQuery.ts:166](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L166) ### Type Parameters @@ -115,10 +179,81 @@ Defined in: [preact-query/src/useQuery.ts:35](https://github.com/TanStack/query/ [`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use — everything you can pass to `useQuery`. + #### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ### Returns [`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\> + +The current query result. `status` is `pending` if there is no cached data and no query attempt +has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to +display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience. + +### Examples + +```tsx +import { queryOptions, useQuery } from '@tanstack/preact-query' + +const postsOptions = queryOptions({ + queryKey: ['posts'], + queryFn: fetchPosts, +}) + +function Posts() { + const { status, data, error, isFetching } = useQuery(postsOptions) + + if (status === 'pending') return 'Loading...' + if (status === 'error') return Error: {error.message} + + return ( +
+ {data.map((post) => ( +

{post.title}

+ ))} +
{isFetching ? 'Background Updating...' : ' '}
+
+ ) +} +``` + +A dependent query, only enabled once `postId` is set: +```tsx +import { useQuery } from '@tanstack/preact-query' + +function Post({ postId }: { postId: number | undefined }) { + const { data } = useQuery({ + queryKey: ['post', postId], + queryFn: () => fetchPost(postId!), + enabled: postId != null, + }) + + return

{data?.title}

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

{data?.title}

+} +``` diff --git a/docs/framework/preact/reference/functions/useQueryClient.md b/docs/framework/preact/reference/functions/useQueryClient.md index 61be8c5af4..65c02ea653 100644 --- a/docs/framework/preact/reference/functions/useQueryClient.md +++ b/docs/framework/preact/reference/functions/useQueryClient.md @@ -7,7 +7,9 @@ title: useQueryClient function useQueryClient(queryClient?): QueryClient; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:10](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L10) +Defined in: [preact-query/src/QueryClientProvider.tsx:20](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L20) + +The `useQueryClient` hook returns the current `QueryClient` instance. ## Parameters @@ -15,6 +17,11 @@ Defined in: [preact-query/src/QueryClientProvider.tsx:10](https://github.com/Tan `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns `QueryClient` + +The current `QueryClient` instance. diff --git a/docs/framework/preact/reference/functions/useQueryErrorResetBoundary.md b/docs/framework/preact/reference/functions/useQueryErrorResetBoundary.md index d9b96677a4..15ec961a2b 100644 --- a/docs/framework/preact/reference/functions/useQueryErrorResetBoundary.md +++ b/docs/framework/preact/reference/functions/useQueryErrorResetBoundary.md @@ -7,8 +7,37 @@ title: useQueryErrorResetBoundary function useQueryErrorResetBoundary(): QueryErrorResetBoundaryValue; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:35](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L35) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:85](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L85) + +This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary +defined it will reset them globally. ## Returns `QueryErrorResetBoundaryValue` + +The boundary's QueryErrorResetBoundaryValue. + +## Example + +```tsx +import { useErrorBoundary } from 'preact/hooks' +import type { ComponentChildren } from 'preact' +import { useQueryErrorResetBoundary } from '@tanstack/preact-query' + +function App({ children }: { children: ComponentChildren }) { + const { reset } = useQueryErrorResetBoundary() + const [error, resetError] = useErrorBoundary(() => reset()) + + if (error) { + return ( +
+ There was an error! + +
+ ) + } + + return children +} +``` diff --git a/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md b/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md index 230d861343..06ffb78381 100644 --- a/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md +++ b/docs/framework/preact/reference/functions/useSuspenseInfiniteQuery.md @@ -7,7 +7,12 @@ title: useSuspenseInfiniteQuery function useSuspenseInfiniteQuery(options, queryClient?): UseSuspenseInfiniteQueryResult; ``` -Defined in: [preact-query/src/useSuspenseInfiniteQuery.ts:18](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseInfiniteQuery.ts#L18) +Defined in: [preact-query/src/useSuspenseInfiniteQuery.ts:66](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseInfiniteQuery.ts#L66) + +The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`, +`enabled`, and `placeholderData`. + +Caveat: cancellation does not work. ## Type Parameters @@ -37,10 +42,55 @@ Defined in: [preact-query/src/useSuspenseInfiniteQuery.ts:18](https://github.com [`UseSuspenseInfiniteQueryOptions`](../interfaces/UseSuspenseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> +The [UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) to use — the same options as `useInfiniteQuery`, minus the ones listed above. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns [`UseSuspenseInfiniteQueryResult`](../type-aliases/UseSuspenseInfiniteQueryResult.md)\<`TData`, `TError`\> + +The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, +`isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set +accordingly). + +## Example + +```tsx +import { Suspense } from 'preact/compat' +import { useSuspenseInfiniteQuery } from '@tanstack/preact-query' + +function Projects() { + // `data` is guaranteed to be defined here — no `isPending` check needed. + const { data, fetchNextPage, hasNextPage } = useSuspenseInfiniteQuery({ + queryKey: ['projects'], + queryFn: ({ pageParam }) => fetchProjects(pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextId, + }) + + return ( +
+ {data.pages.map((page) => + page.projects.map((project) =>

{project.name}

), + )} + +
+ ) +} + +function App() { + return ( + Loading projects...}> + + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/useSuspenseQueries.md b/docs/framework/preact/reference/functions/useSuspenseQueries.md index 7fd0a76497..50b61d6d38 100644 --- a/docs/framework/preact/reference/functions/useSuspenseQueries.md +++ b/docs/framework/preact/reference/functions/useSuspenseQueries.md @@ -9,7 +9,10 @@ title: useSuspenseQueries function useSuspenseQueries(options, queryClient?): TCombinedResult; ``` -Defined in: [preact-query/src/useSuspenseQueries.ts:165](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L165) +Defined in: [preact-query/src/useSuspenseQueries.ts:212](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L212) + +The options for `useSuspenseQueries` are the same as for `useQueries`, except that each `query` can't have +`throwOnError`, `enabled`, or `placeholderData`. ### Type Parameters @@ -25,30 +28,84 @@ Defined in: [preact-query/src/useSuspenseQueries.ts:165](https://github.com/TanS #### options +The `queries` array to run in Suspense, and an optional `combine` function. + ##### combine? (`result`) => `TCombinedResult` +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + ##### queries \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\] \| readonly \[\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryOptions\\]\> \}\] +An array with query option objects identical to `useSuspenseQuery`. + #### queryClient? `QueryClient` +Use this to provide a custom QueryClient. Otherwise, the one from the nearest context +will be used. + ### Returns `TCombinedResult` +The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be +defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived +flags set accordingly). + +Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone +stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid +this, make sure to set a high enough `staleTime`. Cancellation does not work. + +### Example + +```tsx +import { Suspense } from 'preact/compat' +import { useSuspenseQueries } from '@tanstack/preact-query' + +function Posts({ ids }: { ids: Array }) { + // Every result is guaranteed to be defined — no per-query `isPending` check needed. + const results = useSuspenseQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + }) + + return ( +
    + {results.map((result) => ( +
  • {result.data.title}
  • + ))} +
+ ) +} + +function App() { + return ( + Loading posts...}> + + + ) +} +``` + ## Call Signature ```ts function useSuspenseQueries(options, queryClient?): TCombinedResult; ``` -Defined in: [preact-query/src/useSuspenseQueries.ts:178](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L178) +Defined in: [preact-query/src/useSuspenseQueries.ts:279](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L279) + +The options for `useSuspenseQueries` are the same as for `useQueries`, except that each `query` can't have +`throwOnError`, `enabled`, or `placeholderData`. ### Type Parameters @@ -64,18 +121,69 @@ Defined in: [preact-query/src/useSuspenseQueries.ts:178](https://github.com/TanS #### options +The `queries` array to run in Suspense, and an optional `combine` function. + ##### combine? (`result`) => `TCombinedResult` +Use this to combine the results of the queries into a single value. The result will be structurally +shared to be as referentially stable as possible. + ##### queries readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...(...)[]`\] *extends* \[...\] ? \[..., ..., ...\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* \[`...Tails[]`\] ? \[`...Tails[]`\] : \[`...(...)[]`\] *extends* ...[] ? ...[] : ...[] : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]\] +An array with query option objects identical to `useSuspenseQuery`. + #### queryClient? `QueryClient` +Use this to provide a custom QueryClient. Otherwise, the one from the nearest context +will be used. + ### Returns `TCombinedResult` + +The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be +defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived +flags set accordingly). + +Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone +stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid +this, make sure to set a high enough `staleTime`. Cancellation does not work. + +### Example + +```tsx +import { Suspense } from 'preact/compat' +import { useSuspenseQueries } from '@tanstack/preact-query' + +function Posts({ ids }: { ids: Array }) { + // Every result is guaranteed to be defined — no per-query `isPending` check needed. + const results = useSuspenseQueries({ + queries: ids.map((id) => ({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), + })), + }) + + return ( +
    + {results.map((result) => ( +
  • {result.data.title}
  • + ))} +
+ ) +} + +function App() { + return ( + Loading posts...}> + + + ) +} +``` diff --git a/docs/framework/preact/reference/functions/useSuspenseQuery.md b/docs/framework/preact/reference/functions/useSuspenseQuery.md index 7750202206..ee5d805bff 100644 --- a/docs/framework/preact/reference/functions/useSuspenseQuery.md +++ b/docs/framework/preact/reference/functions/useSuspenseQuery.md @@ -7,7 +7,12 @@ title: useSuspenseQuery function useSuspenseQuery(options, queryClient?): UseSuspenseQueryResult; ``` -Defined in: [preact-query/src/useSuspenseQuery.ts:8](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQuery.ts#L8) +Defined in: [preact-query/src/useSuspenseQuery.ts:51](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQuery.ts#L51) + +The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and +`placeholderData`. + +Caveat: cancellation does not work. ## Type Parameters @@ -33,10 +38,50 @@ Defined in: [preact-query/src/useSuspenseQuery.ts:8](https://github.com/TanStack [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> +The [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) to use — the same options as `useQuery`, minus the ones listed above. + ### queryClient? `QueryClient` +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will +be used. + ## Returns [`UseSuspenseQueryResult`](../type-aliases/UseSuspenseQueryResult.md)\<`TData`, `TError`\> + +The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData` +is missing, and `status` is either `success` or `error` (with the derived flags set accordingly). + +## Example + +```tsx +import { Suspense } from 'preact/compat' +import { useSuspenseQuery } from '@tanstack/preact-query' + +function Posts() { + // `data` is guaranteed to be defined here — no `isPending` check needed. + const { data, isFetching } = useSuspenseQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + return ( +
+

Posts {isFetching ? : null}

+ {data.map((post) => ( +

{post.title}

+ ))} +
+ ) +} + +function App() { + return ( + Loading posts...}> + + + ) +} +``` diff --git a/docs/framework/preact/reference/interfaces/HydrationBoundaryProps.md b/docs/framework/preact/reference/interfaces/HydrationBoundaryProps.md index 3470aedf9c..2760f4a917 100644 --- a/docs/framework/preact/reference/interfaces/HydrationBoundaryProps.md +++ b/docs/framework/preact/reference/interfaces/HydrationBoundaryProps.md @@ -13,7 +13,12 @@ Defined in: [preact-query/src/HydrationBoundary.tsx:14](https://github.com/TanSt optional children: ComponentChildren; ``` -Defined in: [preact-query/src/HydrationBoundary.tsx:22](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L22) +Defined in: [preact-query/src/HydrationBoundary.tsx:34](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L34) + +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. *** @@ -23,7 +28,9 @@ Defined in: [preact-query/src/HydrationBoundary.tsx:22](https://github.com/TanSt optional options: OmitKeyof & object; ``` -Defined in: [preact-query/src/HydrationBoundary.tsx:16](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L16) +Defined in: [preact-query/src/HydrationBoundary.tsx:22](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L22) + +Optional. Note: unlike `hydrate`, `mutations` cannot be set here. #### Type Declaration @@ -42,7 +49,9 @@ optional defaultOptions: OmitKeyof<{ optional queryClient: QueryClient; ``` -Defined in: [preact-query/src/HydrationBoundary.tsx:23](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L23) +Defined in: [preact-query/src/HydrationBoundary.tsx:38](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L38) + +Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. *** @@ -52,4 +61,6 @@ Defined in: [preact-query/src/HydrationBoundary.tsx:23](https://github.com/TanSt state: DehydratedState | null | undefined; ``` -Defined in: [preact-query/src/HydrationBoundary.tsx:15](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L15) +Defined in: [preact-query/src/HydrationBoundary.tsx:18](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L18) + +The state to hydrate. diff --git a/docs/framework/preact/reference/interfaces/QueryErrorResetBoundaryProps.md b/docs/framework/preact/reference/interfaces/QueryErrorResetBoundaryProps.md index ea3ebed77e..e9806c8a57 100644 --- a/docs/framework/preact/reference/interfaces/QueryErrorResetBoundaryProps.md +++ b/docs/framework/preact/reference/interfaces/QueryErrorResetBoundaryProps.md @@ -3,7 +3,7 @@ id: QueryErrorResetBoundaryProps title: QueryErrorResetBoundaryProps --- -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:44](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L44) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:100](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L100) ## Properties @@ -15,4 +15,7 @@ children: | QueryErrorResetBoundaryFunction; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:45](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L45) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:105](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L105) + +Either a plain node, or a function that receives the boundary's QueryErrorResetBoundaryValue and +returns a node. diff --git a/docs/framework/preact/reference/interfaces/UseInfiniteQueryOptions.md b/docs/framework/preact/reference/interfaces/UseInfiniteQueryOptions.md index c13265b1ab..570416ab1b 100644 --- a/docs/framework/preact/reference/interfaces/UseInfiniteQueryOptions.md +++ b/docs/framework/preact/reference/interfaces/UseInfiniteQueryOptions.md @@ -3,7 +3,7 @@ id: UseInfiniteQueryOptions title: UseInfiniteQueryOptions --- -Defined in: [preact-query/src/types.ts:139](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L139) +Defined in: [preact-query/src/types.ts:151](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L151) ## Extends @@ -39,7 +39,7 @@ Defined in: [preact-query/src/types.ts:139](https://github.com/TanStack/query/bl optional subscribed: boolean; ``` -Defined in: [preact-query/src/types.ts:159](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L159) +Defined in: [preact-query/src/types.ts:171](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L171) Set this to `false` to unsubscribe this observer from updates to the query cache. Defaults to `true`. diff --git a/docs/framework/preact/reference/interfaces/UseMutationOptions.md b/docs/framework/preact/reference/interfaces/UseMutationOptions.md index fd9c51ee29..13b6dc08a3 100644 --- a/docs/framework/preact/reference/interfaces/UseMutationOptions.md +++ b/docs/framework/preact/reference/interfaces/UseMutationOptions.md @@ -3,7 +3,7 @@ id: UseMutationOptions title: UseMutationOptions --- -Defined in: [preact-query/src/types.ts:228](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L228) +Defined in: [preact-query/src/types.ts:244](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L244) ## Extends diff --git a/docs/framework/preact/reference/interfaces/UseQueryOptions.md b/docs/framework/preact/reference/interfaces/UseQueryOptions.md index 184bf223a7..1038e6c969 100644 --- a/docs/framework/preact/reference/interfaces/UseQueryOptions.md +++ b/docs/framework/preact/reference/interfaces/UseQueryOptions.md @@ -3,7 +3,7 @@ id: UseQueryOptions title: UseQueryOptions --- -Defined in: [preact-query/src/types.ts:101](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L101) +Defined in: [preact-query/src/types.ts:109](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L109) ## Extends diff --git a/docs/framework/preact/reference/interfaces/UseSuspenseInfiniteQueryOptions.md b/docs/framework/preact/reference/interfaces/UseSuspenseInfiniteQueryOptions.md index 08bc5e0b80..34633bf152 100644 --- a/docs/framework/preact/reference/interfaces/UseSuspenseInfiniteQueryOptions.md +++ b/docs/framework/preact/reference/interfaces/UseSuspenseInfiniteQueryOptions.md @@ -3,7 +3,7 @@ id: UseSuspenseInfiniteQueryOptions title: UseSuspenseInfiniteQueryOptions --- -Defined in: [preact-query/src/types.ts:164](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L164) +Defined in: [preact-query/src/types.ts:176](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L176) ## Extends @@ -39,7 +39,10 @@ Defined in: [preact-query/src/types.ts:164](https://github.com/TanStack/query/bl optional queryFn: QueryFunction; ``` -Defined in: [preact-query/src/types.ts:174](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L174) +Defined in: [preact-query/src/types.ts:190](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L190) + +`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. *** @@ -49,7 +52,7 @@ Defined in: [preact-query/src/types.ts:174](https://github.com/TanStack/query/bl optional subscribed: boolean; ``` -Defined in: [preact-query/src/types.ts:159](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L159) +Defined in: [preact-query/src/types.ts:171](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L171) Set this to `false` to unsubscribe this observer from updates to the query cache. Defaults to `true`. diff --git a/docs/framework/preact/reference/interfaces/UseSuspenseQueryOptions.md b/docs/framework/preact/reference/interfaces/UseSuspenseQueryOptions.md index f140aea432..55b0854f7f 100644 --- a/docs/framework/preact/reference/interfaces/UseSuspenseQueryOptions.md +++ b/docs/framework/preact/reference/interfaces/UseSuspenseQueryOptions.md @@ -3,7 +3,7 @@ id: UseSuspenseQueryOptions title: UseSuspenseQueryOptions --- -Defined in: [preact-query/src/types.ts:117](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L117) +Defined in: [preact-query/src/types.ts:125](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L125) ## Extends @@ -35,7 +35,10 @@ Defined in: [preact-query/src/types.ts:117](https://github.com/TanStack/query/bl optional queryFn: QueryFunction; ``` -Defined in: [preact-query/src/types.ts:126](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L126) +Defined in: [preact-query/src/types.ts:138](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L138) + +`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. *** diff --git a/docs/framework/preact/reference/type-aliases/AnyUseInfiniteQueryOptions.md b/docs/framework/preact/reference/type-aliases/AnyUseInfiniteQueryOptions.md index 68ab8da378..ca8ccce2e3 100644 --- a/docs/framework/preact/reference/type-aliases/AnyUseInfiniteQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/AnyUseInfiniteQueryOptions.md @@ -7,4 +7,4 @@ title: AnyUseInfiniteQueryOptions type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions; ``` -Defined in: [preact-query/src/types.ts:132](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L132) +Defined in: [preact-query/src/types.ts:144](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L144) diff --git a/docs/framework/preact/reference/type-aliases/AnyUseMutationOptions.md b/docs/framework/preact/reference/type-aliases/AnyUseMutationOptions.md index d467a5948e..2dc2d26366 100644 --- a/docs/framework/preact/reference/type-aliases/AnyUseMutationOptions.md +++ b/docs/framework/preact/reference/type-aliases/AnyUseMutationOptions.md @@ -7,4 +7,4 @@ title: AnyUseMutationOptions type AnyUseMutationOptions = UseMutationOptions; ``` -Defined in: [preact-query/src/types.ts:227](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L227) +Defined in: [preact-query/src/types.ts:243](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L243) diff --git a/docs/framework/preact/reference/type-aliases/AnyUseQueryOptions.md b/docs/framework/preact/reference/type-aliases/AnyUseQueryOptions.md index 443742b7aa..737779e651 100644 --- a/docs/framework/preact/reference/type-aliases/AnyUseQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/AnyUseQueryOptions.md @@ -7,4 +7,4 @@ title: AnyUseQueryOptions type AnyUseQueryOptions = UseQueryOptions; ``` -Defined in: [preact-query/src/types.ts:100](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L100) +Defined in: [preact-query/src/types.ts:108](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L108) diff --git a/docs/framework/preact/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md b/docs/framework/preact/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md index 61163fa253..045bd4c263 100644 --- a/docs/framework/preact/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/AnyUseSuspenseInfiniteQueryOptions.md @@ -7,4 +7,4 @@ title: AnyUseSuspenseInfiniteQueryOptions type AnyUseSuspenseInfiniteQueryOptions = UseSuspenseInfiniteQueryOptions; ``` -Defined in: [preact-query/src/types.ts:162](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L162) +Defined in: [preact-query/src/types.ts:174](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L174) diff --git a/docs/framework/preact/reference/type-aliases/AnyUseSuspenseQueryOptions.md b/docs/framework/preact/reference/type-aliases/AnyUseSuspenseQueryOptions.md index d74b006fe1..f7b5a6620e 100644 --- a/docs/framework/preact/reference/type-aliases/AnyUseSuspenseQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/AnyUseSuspenseQueryOptions.md @@ -7,4 +7,4 @@ title: AnyUseSuspenseQueryOptions type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions; ``` -Defined in: [preact-query/src/types.ts:111](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L111) +Defined in: [preact-query/src/types.ts:119](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L119) diff --git a/docs/framework/preact/reference/type-aliases/DefinedInitialDataInfiniteOptions.md b/docs/framework/preact/reference/type-aliases/DefinedInitialDataInfiniteOptions.md index 38bd4b91fa..c82ed9d688 100644 --- a/docs/framework/preact/reference/type-aliases/DefinedInitialDataInfiniteOptions.md +++ b/docs/framework/preact/reference/type-aliases/DefinedInitialDataInfiniteOptions.md @@ -7,7 +7,7 @@ title: DefinedInitialDataInfiniteOptions type DefinedInitialDataInfiniteOptions = UseInfiniteQueryOptions & object; ``` -Defined in: [preact-query/src/infiniteQueryOptions.ts:57](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L57) +Defined in: [preact-query/src/infiniteQueryOptions.ts:68](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L68) ## Type Declaration @@ -20,6 +20,12 @@ initialData: | undefined; ``` +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/DefinedInitialDataOptions.md b/docs/framework/preact/reference/type-aliases/DefinedInitialDataOptions.md index d91681471c..111e13a49f 100644 --- a/docs/framework/preact/reference/type-aliases/DefinedInitialDataOptions.md +++ b/docs/framework/preact/reference/type-aliases/DefinedInitialDataOptions.md @@ -7,7 +7,7 @@ title: DefinedInitialDataOptions type DefinedInitialDataOptions = Omit, "queryFn"> & object; ``` -Defined in: [preact-query/src/queryOptions.ts:41](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L41) +Defined in: [preact-query/src/queryOptions.ts:52](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L52) ## Type Declaration @@ -19,12 +19,22 @@ initialData: | () => NonUndefinedGuard; ``` +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + ### queryFn? ```ts optional queryFn: QueryFunction; ``` +Optional here, but omitting it is only safe when no fetch will be attempted — for example with +`enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no +`queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/DefinedUseInfiniteQueryResult.md b/docs/framework/preact/reference/type-aliases/DefinedUseInfiniteQueryResult.md index d822ef4aed..a9d6fd4099 100644 --- a/docs/framework/preact/reference/type-aliases/DefinedUseInfiniteQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/DefinedUseInfiniteQueryResult.md @@ -7,7 +7,7 @@ title: DefinedUseInfiniteQueryResult type DefinedUseInfiniteQueryResult = DefinedInfiniteQueryObserverResult; ``` -Defined in: [preact-query/src/types.ts:214](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L214) +Defined in: [preact-query/src/types.ts:230](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L230) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/DefinedUseQueryResult.md b/docs/framework/preact/reference/type-aliases/DefinedUseQueryResult.md index b49de08fc7..c6803ec059 100644 --- a/docs/framework/preact/reference/type-aliases/DefinedUseQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/DefinedUseQueryResult.md @@ -7,7 +7,7 @@ title: DefinedUseQueryResult type DefinedUseQueryResult = DefinedQueryObserverResult; ``` -Defined in: [preact-query/src/types.ts:204](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L204) +Defined in: [preact-query/src/types.ts:220](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L220) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/QueryClientProviderProps.md b/docs/framework/preact/reference/type-aliases/QueryClientProviderProps.md index 0d835b30c9..9600b35e30 100644 --- a/docs/framework/preact/reference/type-aliases/QueryClientProviderProps.md +++ b/docs/framework/preact/reference/type-aliases/QueryClientProviderProps.md @@ -7,7 +7,7 @@ title: QueryClientProviderProps type QueryClientProviderProps = object; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:24](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L24) +Defined in: [preact-query/src/QueryClientProvider.tsx:34](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L34) ## Properties @@ -17,7 +17,9 @@ Defined in: [preact-query/src/QueryClientProvider.tsx:24](https://github.com/Tan optional children: ComponentChildren; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:26](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L26) +Defined in: [preact-query/src/QueryClientProvider.tsx:44](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L44) + +The components that get access to the provided QueryClient. *** @@ -27,4 +29,8 @@ Defined in: [preact-query/src/QueryClientProvider.tsx:26](https://github.com/Tan client: QueryClient; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:25](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L25) +Defined in: [preact-query/src/QueryClientProvider.tsx:40](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L40) + +**Required** + +The QueryClient instance to provide. diff --git a/docs/framework/preact/reference/type-aliases/QueryErrorClearResetFunction.md b/docs/framework/preact/reference/type-aliases/QueryErrorClearResetFunction.md index 26cbffd963..d80f43bf5e 100644 --- a/docs/framework/preact/reference/type-aliases/QueryErrorClearResetFunction.md +++ b/docs/framework/preact/reference/type-aliases/QueryErrorClearResetFunction.md @@ -7,7 +7,9 @@ title: QueryErrorClearResetFunction type QueryErrorClearResetFunction = () => void; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:8](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L8) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:20](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L20) + +Clears the reset state, so queries know not to try again until the boundary is reset again. ## Returns diff --git a/docs/framework/preact/reference/type-aliases/QueryErrorIsResetFunction.md b/docs/framework/preact/reference/type-aliases/QueryErrorIsResetFunction.md index 3c08a571ff..c1cd3ca73e 100644 --- a/docs/framework/preact/reference/type-aliases/QueryErrorIsResetFunction.md +++ b/docs/framework/preact/reference/type-aliases/QueryErrorIsResetFunction.md @@ -7,7 +7,9 @@ title: QueryErrorIsResetFunction type QueryErrorIsResetFunction = () => boolean; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:7](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L7) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:15](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L15) + +Returns whether the boundary has been reset and not yet cleared. ## Returns diff --git a/docs/framework/preact/reference/type-aliases/QueryErrorResetBoundaryFunction.md b/docs/framework/preact/reference/type-aliases/QueryErrorResetBoundaryFunction.md index 4d6027cea0..2ed65c16cb 100644 --- a/docs/framework/preact/reference/type-aliases/QueryErrorResetBoundaryFunction.md +++ b/docs/framework/preact/reference/type-aliases/QueryErrorResetBoundaryFunction.md @@ -7,7 +7,9 @@ title: QueryErrorResetBoundaryFunction type QueryErrorResetBoundaryFunction = (value) => ComponentChildren; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:40](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L40) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:96](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L96) + +A render-prop function usable as `children` on `QueryErrorResetBoundary`. ## Parameters @@ -15,6 +17,10 @@ Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:40](https://github.com `QueryErrorResetBoundaryValue` +The boundary's QueryErrorResetBoundaryValue. + ## Returns `ComponentChildren` + +The children to render. diff --git a/docs/framework/preact/reference/type-aliases/QueryErrorResetFunction.md b/docs/framework/preact/reference/type-aliases/QueryErrorResetFunction.md index 09ad00e7f9..963e0bba8a 100644 --- a/docs/framework/preact/reference/type-aliases/QueryErrorResetFunction.md +++ b/docs/framework/preact/reference/type-aliases/QueryErrorResetFunction.md @@ -7,7 +7,9 @@ title: QueryErrorResetFunction type QueryErrorResetFunction = () => void; ``` -Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:6](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L6) +Defined in: [preact-query/src/QueryErrorResetBoundary.tsx:10](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L10) + +Resets any query errors within the boundary, so queries know they can try again. ## Returns diff --git a/docs/framework/preact/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md b/docs/framework/preact/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md index 74d4863c67..a36016349f 100644 --- a/docs/framework/preact/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md +++ b/docs/framework/preact/reference/type-aliases/UndefinedInitialDataInfiniteOptions.md @@ -19,6 +19,12 @@ optional initialData: | InitialDataFunction>>; ``` +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UndefinedInitialDataOptions.md b/docs/framework/preact/reference/type-aliases/UndefinedInitialDataOptions.md index 97523af511..6f6a4cae55 100644 --- a/docs/framework/preact/reference/type-aliases/UndefinedInitialDataOptions.md +++ b/docs/framework/preact/reference/type-aliases/UndefinedInitialDataOptions.md @@ -19,6 +19,12 @@ optional initialData: | NonUndefinedGuard; ``` +If set, this value will be used as the initial data for the query cache (as long as the query hasn't been +created or cached yet). If set to a function, the function will be called **once** during the shared/root +query initialization, and be expected to synchronously return the initial data. Initial data is +considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the +cache. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md b/docs/framework/preact/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md index d5a6f8a455..78c039445f 100644 --- a/docs/framework/preact/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md +++ b/docs/framework/preact/reference/type-aliases/UnusedSkipTokenInfiniteOptions.md @@ -7,7 +7,7 @@ title: UnusedSkipTokenInfiniteOptions type UnusedSkipTokenInfiniteOptions = OmitKeyof, "queryFn"> & object; ``` -Defined in: [preact-query/src/infiniteQueryOptions.ts:35](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L35) +Defined in: [preact-query/src/infiniteQueryOptions.ts:42](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L42) ## Type Declaration @@ -17,6 +17,9 @@ Defined in: [preact-query/src/infiniteQueryOptions.ts:35](https://github.com/Tan optional queryFn: Exclude["queryFn"], SkipToken | undefined>; ``` +`skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If +you don't intend to run the query yet, omit `queryFn` or use a default query function instead. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UnusedSkipTokenOptions.md b/docs/framework/preact/reference/type-aliases/UnusedSkipTokenOptions.md index f298f01c8c..7f82dad99c 100644 --- a/docs/framework/preact/reference/type-aliases/UnusedSkipTokenOptions.md +++ b/docs/framework/preact/reference/type-aliases/UnusedSkipTokenOptions.md @@ -7,7 +7,7 @@ title: UnusedSkipTokenOptions type UnusedSkipTokenOptions = OmitKeyof, "queryFn"> & object; ``` -Defined in: [preact-query/src/queryOptions.ts:26](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L26) +Defined in: [preact-query/src/queryOptions.ts:33](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L33) ## Type Declaration @@ -17,6 +17,9 @@ Defined in: [preact-query/src/queryOptions.ts:26](https://github.com/TanStack/qu optional queryFn: Exclude["queryFn"], SkipToken | undefined>; ``` +`skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If +you don't intend to run the query yet, omit `queryFn` or use a default query function instead. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UseBaseMutationResult.md b/docs/framework/preact/reference/type-aliases/UseBaseMutationResult.md index 603ed6faf3..47bfb391d1 100644 --- a/docs/framework/preact/reference/type-aliases/UseBaseMutationResult.md +++ b/docs/framework/preact/reference/type-aliases/UseBaseMutationResult.md @@ -9,7 +9,7 @@ type UseBaseMutationResult = Overrid }> & object; ``` -Defined in: [preact-query/src/types.ts:256](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L256) +Defined in: [preact-query/src/types.ts:281](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L281) ## Type Declaration @@ -19,6 +19,8 @@ Defined in: [preact-query/src/types.ts:256](https://github.com/TanStack/query/bl mutateAsync: UseMutateAsyncFunction; ``` +Similar to `mutate`, but returns a promise which can be awaited. + ## Type Parameters ### TData diff --git a/docs/framework/preact/reference/type-aliases/UseBaseQueryResult.md b/docs/framework/preact/reference/type-aliases/UseBaseQueryResult.md index b93999edcb..70bf3f5252 100644 --- a/docs/framework/preact/reference/type-aliases/UseBaseQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/UseBaseQueryResult.md @@ -7,7 +7,7 @@ title: UseBaseQueryResult type UseBaseQueryResult = QueryObserverResult; ``` -Defined in: [preact-query/src/types.ts:186](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L186) +Defined in: [preact-query/src/types.ts:202](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L202) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseInfiniteQueryResult.md b/docs/framework/preact/reference/type-aliases/UseInfiniteQueryResult.md index a0a7cfe492..9b0b9eec23 100644 --- a/docs/framework/preact/reference/type-aliases/UseInfiniteQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/UseInfiniteQueryResult.md @@ -7,7 +7,7 @@ title: UseInfiniteQueryResult type UseInfiniteQueryResult = InfiniteQueryObserverResult; ``` -Defined in: [preact-query/src/types.ts:209](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L209) +Defined in: [preact-query/src/types.ts:225](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L225) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseMutateAsyncFunction.md b/docs/framework/preact/reference/type-aliases/UseMutateAsyncFunction.md index 3e3b26c24f..8a833c776a 100644 --- a/docs/framework/preact/reference/type-aliases/UseMutateAsyncFunction.md +++ b/docs/framework/preact/reference/type-aliases/UseMutateAsyncFunction.md @@ -7,7 +7,10 @@ title: UseMutateAsyncFunction type UseMutateAsyncFunction = MutateFunction; ``` -Defined in: [preact-query/src/types.ts:249](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L249) +Defined in: [preact-query/src/types.ts:274](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L274) + +The type of `mutateAsync`, as returned by `useMutation`. Similar to [UseMutateFunction](UseMutateFunction.md), but returns a +promise which can be awaited. ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseMutateFunction.md b/docs/framework/preact/reference/type-aliases/UseMutateFunction.md index d38ea3e0aa..5f692a4239 100644 --- a/docs/framework/preact/reference/type-aliases/UseMutateFunction.md +++ b/docs/framework/preact/reference/type-aliases/UseMutateFunction.md @@ -7,7 +7,11 @@ title: UseMutateFunction type UseMutateFunction = (...args) => void; ``` -Defined in: [preact-query/src/types.ts:238](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L238) +Defined in: [preact-query/src/types.ts:259](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L259) + +The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call +`onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced +through the mutation result, not thrown. ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseMutationResult.md b/docs/framework/preact/reference/type-aliases/UseMutationResult.md index b84dd9fe85..2611e9a1ef 100644 --- a/docs/framework/preact/reference/type-aliases/UseMutationResult.md +++ b/docs/framework/preact/reference/type-aliases/UseMutationResult.md @@ -7,7 +7,7 @@ title: UseMutationResult type UseMutationResult = UseBaseMutationResult; ``` -Defined in: [preact-query/src/types.ts:273](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L273) +Defined in: [preact-query/src/types.ts:301](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L301) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md b/docs/framework/preact/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md index a8a5e15acc..a1bae7e8ce 100644 --- a/docs/framework/preact/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/UsePrefetchInfiniteQueryOptions.md @@ -7,7 +7,7 @@ title: UsePrefetchInfiniteQueryOptions type UsePrefetchInfiniteQueryOptions = DistributiveOmit, "queryFn"> & object; ``` -Defined in: [preact-query/src/types.ts:72](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L72) +Defined in: [preact-query/src/types.ts:76](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L76) ## Type Declaration @@ -17,6 +17,9 @@ Defined in: [preact-query/src/types.ts:72](https://github.com/TanStack/query/blo optional queryFn: Exclude["queryFn"], SkipToken>; ``` +`skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, +unless a default query function has been defined. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UsePrefetchQueryOptions.md b/docs/framework/preact/reference/type-aliases/UsePrefetchQueryOptions.md index 12023e9d75..174c48f9c4 100644 --- a/docs/framework/preact/reference/type-aliases/UsePrefetchQueryOptions.md +++ b/docs/framework/preact/reference/type-aliases/UsePrefetchQueryOptions.md @@ -17,6 +17,9 @@ Defined in: [preact-query/src/types.ts:50](https://github.com/TanStack/query/blo optional queryFn: Exclude["queryFn"], SkipToken>; ``` +`skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, +unless a default query function has been defined. + ## Type Parameters ### TQueryFnData diff --git a/docs/framework/preact/reference/type-aliases/UseQueryResult.md b/docs/framework/preact/reference/type-aliases/UseQueryResult.md index 8c3a3f7e31..7a52ca3e89 100644 --- a/docs/framework/preact/reference/type-aliases/UseQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/UseQueryResult.md @@ -7,7 +7,7 @@ title: UseQueryResult type UseQueryResult = UseBaseQueryResult; ``` -Defined in: [preact-query/src/types.ts:191](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L191) +Defined in: [preact-query/src/types.ts:207](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L207) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseSuspenseInfiniteQueryResult.md b/docs/framework/preact/reference/type-aliases/UseSuspenseInfiniteQueryResult.md index 5f5db5b1bd..dedb0fe4f9 100644 --- a/docs/framework/preact/reference/type-aliases/UseSuspenseInfiniteQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/UseSuspenseInfiniteQueryResult.md @@ -7,7 +7,7 @@ title: UseSuspenseInfiniteQueryResult type UseSuspenseInfiniteQueryResult = OmitKeyof, "isPlaceholderData">; ``` -Defined in: [preact-query/src/types.ts:219](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L219) +Defined in: [preact-query/src/types.ts:235](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L235) ## Type Parameters diff --git a/docs/framework/preact/reference/type-aliases/UseSuspenseQueryResult.md b/docs/framework/preact/reference/type-aliases/UseSuspenseQueryResult.md index 42320c3f6f..34fed72a54 100644 --- a/docs/framework/preact/reference/type-aliases/UseSuspenseQueryResult.md +++ b/docs/framework/preact/reference/type-aliases/UseSuspenseQueryResult.md @@ -7,7 +7,7 @@ title: UseSuspenseQueryResult type UseSuspenseQueryResult = DistributiveOmit, "isPlaceholderData">; ``` -Defined in: [preact-query/src/types.ts:196](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L196) +Defined in: [preact-query/src/types.ts:212](https://github.com/TanStack/query/blob/main/packages/preact-query/src/types.ts#L212) ## Type Parameters diff --git a/docs/framework/preact/reference/variables/IsRestoringProvider.md b/docs/framework/preact/reference/variables/IsRestoringProvider.md index e7844f01c8..42069e45fc 100644 --- a/docs/framework/preact/reference/variables/IsRestoringProvider.md +++ b/docs/framework/preact/reference/variables/IsRestoringProvider.md @@ -7,4 +7,7 @@ title: IsRestoringProvider const IsRestoringProvider: Provider = IsRestoringContext.Provider; ``` -Defined in: [preact-query/src/IsRestoringProvider.ts:7](https://github.com/TanStack/query/blob/main/packages/preact-query/src/IsRestoringProvider.ts#L7) +Defined in: [preact-query/src/IsRestoringProvider.ts:19](https://github.com/TanStack/query/blob/main/packages/preact-query/src/IsRestoringProvider.ts#L19) + +The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently +being restored, read by `useIsRestoring`. diff --git a/docs/framework/preact/reference/variables/QueryClientContext.md b/docs/framework/preact/reference/variables/QueryClientContext.md index ea5b0b0708..fa7a465d17 100644 --- a/docs/framework/preact/reference/variables/QueryClientContext.md +++ b/docs/framework/preact/reference/variables/QueryClientContext.md @@ -7,4 +7,6 @@ title: QueryClientContext const QueryClientContext: Context; ``` -Defined in: [preact-query/src/QueryClientProvider.tsx:6](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L6) +Defined in: [preact-query/src/QueryClientProvider.tsx:9](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L9) + +The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/packages/preact-query/src/HydrationBoundary.tsx b/packages/preact-query/src/HydrationBoundary.tsx index 40277bc06b..cb6950adb7 100644 --- a/packages/preact-query/src/HydrationBoundary.tsx +++ b/packages/preact-query/src/HydrationBoundary.tsx @@ -12,17 +12,76 @@ import { useEffect, useMemo, useRef } from 'preact/hooks' import { useQueryClient } from './QueryClientProvider' export interface HydrationBoundaryProps { + /** + * The state to hydrate. + */ state: DehydratedState | null | undefined + /** + * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + */ options?: OmitKeyof & { defaultOptions?: OmitKeyof< Exclude, 'mutations' > } + /** + * 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. + */ children?: ComponentChildren + /** + * Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used. + */ queryClient?: QueryClient } +/** + * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by + * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on + * update timestamp. + * + * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + * + * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the + * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect + * after commit. + * + * @example + * ```tsx + * import { HydrationBoundary } from '@tanstack/preact-query' + * + * function App() { + * return ... + * } + * ``` + * + * @example + * Server-side prefetch handed off to the client via `dehydrate`: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { HydrationBoundary, dehydrate } from '@tanstack/preact-query' + * + * async function ServerComponent() { + * const queryClient = getQueryClient() + * + * await queryClient + * .query({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * .catch(noop) + * + * return ( + * + * + * + * ) + * } + * ``` + */ export const HydrationBoundary = ({ children, options = {}, diff --git a/packages/preact-query/src/IsRestoringProvider.ts b/packages/preact-query/src/IsRestoringProvider.ts index a412ada08d..e2c240eba3 100644 --- a/packages/preact-query/src/IsRestoringProvider.ts +++ b/packages/preact-query/src/IsRestoringProvider.ts @@ -3,5 +3,17 @@ import { useContext } from 'preact/hooks' const IsRestoringContext = createContext(false) +/** + * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to + * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid + * race conditions between the restore and mounting queries. + * + * @returns `true` while a persisted client is being restored, `false` otherwise. + */ export const useIsRestoring = () => useContext(IsRestoringContext) + +/** + * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently + * being restored, read by `useIsRestoring`. + */ export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/preact-query/src/QueryClientProvider.tsx b/packages/preact-query/src/QueryClientProvider.tsx index b4a1dfa1b5..9c607d1286 100644 --- a/packages/preact-query/src/QueryClientProvider.tsx +++ b/packages/preact-query/src/QueryClientProvider.tsx @@ -3,10 +3,20 @@ import { createContext } from 'preact' import type { ComponentChildren, VNode } from 'preact' import { useContext, useEffect } from 'preact/hooks' +/** + * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. + */ export const QueryClientContext = createContext( undefined, ) +/** + * The `useQueryClient` hook returns the current `QueryClient` instance. + * + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The current `QueryClient` instance. + */ export const useQueryClient = (queryClient?: QueryClient) => { const client = useContext(QueryClientContext) @@ -22,10 +32,34 @@ export const useQueryClient = (queryClient?: QueryClient) => { } export type QueryClientProviderProps = { + /** + * **Required** + * + * The QueryClient instance to provide. + */ client: QueryClient + /** + * The components that get access to the provided QueryClient. + */ children?: ComponentChildren } +/** + * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. + * + * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + * + * @example + * ```tsx + * import { QueryClient, QueryClientProvider } from '@tanstack/preact-query' + * + * const queryClient = new QueryClient() + * + * function App() { + * return ... + * } + * ``` + */ export const QueryClientProvider = ({ client, children, diff --git a/packages/preact-query/src/QueryErrorResetBoundary.tsx b/packages/preact-query/src/QueryErrorResetBoundary.tsx index ed038bc31b..02ace5ddda 100644 --- a/packages/preact-query/src/QueryErrorResetBoundary.tsx +++ b/packages/preact-query/src/QueryErrorResetBoundary.tsx @@ -3,13 +3,34 @@ import type { ComponentChildren } from 'preact' import { useContext, useState } from 'preact/hooks' // CONTEXT + +/** + * Resets any query errors within the boundary, so queries know they can try again. + */ export type QueryErrorResetFunction = () => void + +/** + * Returns whether the boundary has been reset and not yet cleared. + */ export type QueryErrorIsResetFunction = () => boolean + +/** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ export type QueryErrorClearResetFunction = () => void export interface QueryErrorResetBoundaryValue { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ clearReset: QueryErrorClearResetFunction + /** + * Returns whether the boundary has been reset and not yet cleared. + */ isReset: QueryErrorIsResetFunction + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ reset: QueryErrorResetFunction } @@ -32,19 +53,104 @@ const QueryErrorResetBoundaryContext = createContext(createValue()) // HOOK +/** + * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary + * defined it will reset them globally. + * + * @returns The boundary's {@link QueryErrorResetBoundaryValue}. + * + * @example + * ```tsx + * import { useErrorBoundary } from 'preact/hooks' + * import type { ComponentChildren } from 'preact' + * import { useQueryErrorResetBoundary } from '@tanstack/preact-query' + * + * function App({ children }: { children: ComponentChildren }) { + * const { reset } = useQueryErrorResetBoundary() + * const [error, resetError] = useErrorBoundary(() => reset()) + * + * if (error) { + * return ( + *
+ * There was an error! + * + *
+ * ) + * } + * + * return children + * } + * ``` + */ export const useQueryErrorResetBoundary = () => useContext(QueryErrorResetBoundaryContext) // COMPONENT +/** + * A render-prop function usable as `children` on `QueryErrorResetBoundary`. + * + * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. + * @returns The children to render. + */ export type QueryErrorResetBoundaryFunction = ( value: QueryErrorResetBoundaryValue, ) => ComponentChildren export interface QueryErrorResetBoundaryProps { + /** + * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and + * returns a node. + */ children: QueryErrorResetBoundaryFunction | ComponentChildren } +/** + * When using **suspense** or **throwOnError** in your queries, you need a way to let queries know that you want to + * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can + * reset any query errors within the boundaries of the component. + * + * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} + * if `children` is a function. + * + * @example + * ```tsx + * import { useErrorBoundary } from 'preact/hooks' + * import type { ComponentChildren } from 'preact' + * import { QueryErrorResetBoundary } from '@tanstack/preact-query' + * + * function ErrorBoundary({ + * children, + * reset, + * }: { + * children: ComponentChildren + * reset: () => void + * }) { + * const [error, resetError] = useErrorBoundary(() => reset()) + * + * if (error) { + * return ( + *
+ * There was an error! + * + *
+ * ) + * } + * + * return children + * } + * + * const App = () => ( + * + * {({ reset }) => ( + * + * + * + * )} + * + * ) + * ``` + */ export const QueryErrorResetBoundary = ({ children, }: QueryErrorResetBoundaryProps) => { diff --git a/packages/preact-query/src/infiniteQueryOptions.ts b/packages/preact-query/src/infiniteQueryOptions.ts index 660f00b1de..081e35e2ed 100644 --- a/packages/preact-query/src/infiniteQueryOptions.ts +++ b/packages/preact-query/src/infiniteQueryOptions.ts @@ -24,6 +24,13 @@ export type UndefinedInitialDataInfiniteOptions< TQueryKey, TPageParam > & { + /** + * 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. + */ initialData?: | undefined | NonUndefinedGuard> @@ -42,6 +49,10 @@ export type UnusedSkipTokenInfiniteOptions< UseInfiniteQueryOptions, 'queryFn' > & { + /** + * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If + * you don't intend to run the query yet, omit `queryFn` or use a default query function instead. + */ queryFn?: Exclude< UseInfiniteQueryOptions< TQueryFnData, @@ -67,12 +78,47 @@ export type DefinedInitialDataInfiniteOptions< TQueryKey, TPageParam > & { + /** + * 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. + */ initialData: | NonUndefinedGuard> | (() => NonUndefinedGuard>) | undefined } +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is set. + * + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * const { data } = useInfiniteQuery(projectsOptions) + * return <>{data.pages.map((page) => page.projects.map((p) =>

{p.name}

))} + * } + * ``` + */ export function infiniteQueryOptions< TQueryFnData, TError = DefaultError, @@ -96,6 +142,55 @@ export function infiniteQueryOptions< > & QueryKeyWithDataTag, TError> +/** + * 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. + * + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { infiniteQueryOptions } from '@tanstack/preact-query' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * ``` + * + * @example + * A parameterized factory, reused across a hook and an imperative call with the same cache entry: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const result = useInfiniteQuery(commentsOptions(postId)) + * if (!result.isSuccess) return 'Loading...' + * return ( + * <> + * {result.data.pages.map((page) => page.comments.map((c) =>

{c.text}

))} + * + * ) + * } + * + * // Elsewhere, e.g. to warm the cache before rendering ``: + * queryClient.infiniteQuery(commentsOptions(postId)).catch(noop) + * ``` + * + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + */ export function infiniteQueryOptions< TQueryFnData, TError = DefaultError, @@ -119,6 +214,55 @@ export function infiniteQueryOptions< > & QueryKeyWithDataTag, TError> +/** + * 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. + * + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { infiniteQueryOptions } from '@tanstack/preact-query' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * ``` + * + * @example + * A parameterized factory, reused across a hook and an imperative call with the same cache entry: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const result = useInfiniteQuery(commentsOptions(postId)) + * if (!result.isSuccess) return 'Loading...' + * return ( + * <> + * {result.data.pages.map((page) => page.comments.map((c) =>

{c.text}

))} + * + * ) + * } + * + * // Elsewhere, e.g. to warm the cache before rendering ``: + * queryClient.infiniteQuery(commentsOptions(postId)).catch(noop) + * ``` + * + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + */ export function infiniteQueryOptions< TQueryFnData, TError = DefaultError, diff --git a/packages/preact-query/src/mutationOptions.ts b/packages/preact-query/src/mutationOptions.ts index 5c926a7e3d..ffabea5a75 100644 --- a/packages/preact-query/src/mutationOptions.ts +++ b/packages/preact-query/src/mutationOptions.ts @@ -2,6 +2,49 @@ import type { DefaultError, WithRequired } from '@tanstack/query-core' import type { UseMutationOptions } from './types' +/** + * 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`. + * + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/preact-query' + * + * export const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + * + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/preact-query' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ export function mutationOptions< TData = unknown, TError = DefaultError, @@ -16,6 +59,29 @@ export function mutationOptions< UseMutationOptions, 'mutationKey' > +/** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to look the mutation up later + * (e.g. with `useMutationState`). + * + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/preact-query' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ export function mutationOptions< TData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/queryOptions.ts b/packages/preact-query/src/queryOptions.ts index 3b61de0912..32ddec4f1d 100644 --- a/packages/preact-query/src/queryOptions.ts +++ b/packages/preact-query/src/queryOptions.ts @@ -17,6 +17,13 @@ export type UndefinedInitialDataOptions< TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > = UseQueryOptions & { + /** + * 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. + */ initialData?: | undefined | InitialDataFunction> @@ -32,6 +39,10 @@ export type UnusedSkipTokenOptions< UseQueryOptions, 'queryFn' > & { + /** + * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If + * you don't intend to run the query yet, omit `queryFn` or use a default query function instead. + */ queryFn?: Exclude< UseQueryOptions['queryFn'], SkipToken | undefined @@ -44,12 +55,51 @@ export type DefinedInitialDataOptions< TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > = Omit, 'queryFn'> & { + /** + * 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. + */ initialData: | NonUndefinedGuard | (() => NonUndefinedGuard) + /** + * Optional here, but omitting it is only safe when no fetch will be attempted — for example with + * `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no + * `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this. + */ queryFn?: QueryFunction } +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. + * + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/preact-query' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData`. + * const { data } = useQuery(postsOptions) + * return <>{data.map((post) =>

{post.title}

)} + * } + * ``` + */ export function queryOptions< TQueryFnData = unknown, TError = DefaultError, @@ -60,6 +110,62 @@ export function queryOptions< ): DefinedInitialDataOptions & QueryKeyWithDataTag +/** + * 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. + * + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { queryOptions } from '@tanstack/preact-query' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + * + * @example + * A parameterized factory, reused across a hook and an imperative call with the same cache entry: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { queryOptions, useQuery } from '@tanstack/preact-query' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data } = useQuery(postOptions(id)) + * return

{data?.title}

+ * } + * + * // Elsewhere, e.g. to warm the cache before rendering ``: + * queryClient.query(postOptions(id)).catch(noop) + * ``` + * + * @example + * The same options object works with every API that accepts query options: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { queryOptions, useQuery, useSuspenseQuery } from '@tanstack/preact-query' + * + * const todosOptions = queryOptions({ + * queryKey: ['todos'], + * queryFn: fetchTodos, + * }) + * + * useQuery(todosOptions) + * useSuspenseQuery(todosOptions) + * queryClient.query(todosOptions).catch(noop) + * queryClient.getQueryData(todosOptions.queryKey) // typed as Array | undefined + * ``` + */ export function queryOptions< TQueryFnData = unknown, TError = DefaultError, @@ -70,6 +176,62 @@ export function queryOptions< ): UnusedSkipTokenOptions & QueryKeyWithDataTag +/** + * 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. + * + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * + * @example + * ```tsx + * import { queryOptions } from '@tanstack/preact-query' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + * + * @example + * A parameterized factory, reused across a hook and an imperative call with the same cache entry: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { queryOptions, useQuery } from '@tanstack/preact-query' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data } = useQuery(postOptions(id)) + * return

{data?.title}

+ * } + * + * // Elsewhere, e.g. to warm the cache before rendering ``: + * queryClient.query(postOptions(id)).catch(noop) + * ``` + * + * @example + * The same options object works with every API that accepts query options: + * ```tsx + * import { noop } from '@tanstack/query-core' + * import { queryOptions, useQuery, useSuspenseQuery } from '@tanstack/preact-query' + * + * const todosOptions = queryOptions({ + * queryKey: ['todos'], + * queryFn: fetchTodos, + * }) + * + * useQuery(todosOptions) + * useSuspenseQuery(todosOptions) + * queryClient.query(todosOptions).catch(noop) + * queryClient.getQueryData(todosOptions.queryKey) // typed as Array | undefined + * ``` + */ export function queryOptions< TQueryFnData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/types.ts b/packages/preact-query/src/types.ts index 9a9b646e9e..c23cbf38f9 100644 --- a/packages/preact-query/src/types.ts +++ b/packages/preact-query/src/types.ts @@ -57,6 +57,10 @@ export type UsePrefetchQueryOptions< QueryExecuteOptions, 'queryFn' > & { + /** + * `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, + * unless a default query function has been defined. + */ queryFn?: Exclude< QueryExecuteOptions< TQueryFnData, @@ -85,6 +89,10 @@ export type UsePrefetchInfiniteQueryOptions< >, 'queryFn' > & { + /** + * `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run, + * unless a default query function has been defined. + */ queryFn?: Exclude< InfiniteQueryExecuteOptions< TQueryFnData, @@ -123,6 +131,10 @@ export interface UseSuspenseQueryOptions< UseQueryOptions, 'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData' > { + /** + * `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. + */ queryFn?: Exclude< UseQueryOptions['queryFn'], SkipToken @@ -171,6 +183,10 @@ export interface UseSuspenseInfiniteQueryOptions< UseInfiniteQueryOptions, 'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData' > { + /** + * `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. + */ queryFn?: Exclude< UseInfiniteQueryOptions< TQueryFnData, @@ -235,6 +251,11 @@ export interface UseMutationOptions< '_defaulted' > {} +/** + * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call + * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced + * through the mutation result, not thrown. + */ export type UseMutateFunction< TData = unknown, TError = DefaultError, @@ -246,6 +267,10 @@ export type UseMutateFunction< > ) => void +/** + * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a + * promise which can be awaited. + */ export type UseMutateAsyncFunction< TData = unknown, TError = DefaultError, @@ -262,6 +287,9 @@ export type UseBaseMutationResult< MutationObserverResult, { mutate: UseMutateFunction } > & { + /** + * Similar to `mutate`, but returns a promise which can be awaited. + */ mutateAsync: UseMutateAsyncFunction< TData, TError, diff --git a/packages/preact-query/src/useInfiniteQuery.ts b/packages/preact-query/src/useInfiniteQuery.ts index f78c14a237..95d2db3c02 100644 --- a/packages/preact-query/src/useInfiniteQuery.ts +++ b/packages/preact-query/src/useInfiniteQuery.ts @@ -18,6 +18,36 @@ import type { } from './types' import { useBaseQuery } from './useBaseQuery' +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * This overload is selected when `initialData` is set. + * + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, + * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and + * `isFetchingPreviousPage`. + * + * @example + * ```tsx + * import { useInfiniteQuery } from '@tanstack/preact-query' + * + * function Projects() { + * const { data } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * return <>{data.pages.map((page) => page.projects.map((p) =>

{p.name}

))} + * } + * ``` + */ export function useInfiniteQuery< TQueryFnData, TError = DefaultError, @@ -35,6 +65,43 @@ export function useInfiniteQuery< queryClient?: QueryClient, ): DefinedUseInfiniteQueryResult +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, + * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and + * `isFetchingPreviousPage`. + * + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Projects() { + * const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = + * useInfiniteQuery(projectsOptions) + * + * return ( + * + * ) + * } + * ``` + */ export function useInfiniteQuery< TQueryFnData, TError = DefaultError, @@ -52,6 +119,47 @@ export function useInfiniteQuery< queryClient?: QueryClient, ): UseInfiniteQueryResult +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of `queryFn`, + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch + * behavior, resulting in outdated data. Make sure to call these functions only in response to user actions, + * or add conditions like `hasNextPage && !isFetching`. + * + * @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `data.pages`, `data.pageParams`, + * `fetchNextPage`, `fetchPreviousPage`, `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and + * `isFetchingPreviousPage`. + * + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Projects() { + * const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = + * useInfiniteQuery(projectsOptions) + * + * return ( + * + * ) + * } + * ``` + */ export function useInfiniteQuery< TQueryFnData, TError = DefaultError, diff --git a/packages/preact-query/src/useIsFetching.ts b/packages/preact-query/src/useIsFetching.ts index 07be71c595..877cc068aa 100644 --- a/packages/preact-query/src/useIsFetching.ts +++ b/packages/preact-query/src/useIsFetching.ts @@ -5,6 +5,26 @@ import { useCallback } from 'preact/hooks' import { useQueryClient } from './QueryClientProvider' import { useSyncExternalStore } from './utils' +/** + * `useIsFetching` is an optional hook that returns the `number` of the queries that your application is loading or + * fetching in the background (useful for app-wide loading indicators). + * + * @param filters - The {@link QueryFilters} to narrow down the matched queries. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the queries that your application is currently loading or fetching in the + * background. + * + * @example + * ```tsx + * import { useIsFetching } from '@tanstack/preact-query' + * + * // How many queries are fetching? + * const isFetching = useIsFetching() + * // How many queries matching the posts prefix are fetching? + * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + * ``` + */ export function useIsFetching( filters?: QueryFilters, queryClient?: QueryClient, diff --git a/packages/preact-query/src/useMutation.ts b/packages/preact-query/src/useMutation.ts index 495aaadd91..23523885dc 100644 --- a/packages/preact-query/src/useMutation.ts +++ b/packages/preact-query/src/useMutation.ts @@ -17,6 +17,72 @@ import { useSyncExternalStore } from './utils' // HOOK +/** + * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. + * `useMutation` is the hook for that. + * + * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second + * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared + * mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've + * made. + * + * @example + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/preact-query' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * return ( + * + * ) + * } + * ``` + * + * @example + * Optimistic update via `onMutate`, rolling back on `onError`: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/preact-query' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onMutate: async (newTodo) => { + * await queryClient.cancelQueries({ queryKey: ['todos'] }) + * const previousTodos = queryClient.getQueryData>(['todos']) + * + * queryClient.setQueryData>(['todos'], (old) => [ + * ...(old ?? []), + * newTodo, + * ]) + * + * // Passed to `onError` as `context` if the mutation fails. + * return { previousTodos } + * }, + * onError: (_err, _newTodo, context) => { + * queryClient.setQueryData(['todos'], context?.previousTodos) + * }, + * onSettled: () => { + * queryClient.invalidateQueries({ queryKey: ['todos'] }) + * }, + * }) + * + * return ( + * + * ) + * } + * ``` + */ export function useMutation< TData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/useMutationState.ts b/packages/preact-query/src/useMutationState.ts index b998467925..342c49c385 100644 --- a/packages/preact-query/src/useMutationState.ts +++ b/packages/preact-query/src/useMutationState.ts @@ -11,6 +11,25 @@ import { useCallback, useEffect, useRef } from 'preact/hooks' import { useQueryClient } from './QueryClientProvider' import { useSyncExternalStore } from './utils' +/** + * `useIsMutating` is an optional hook that returns the `number` of mutations that your application is fetching + * (useful for app-wide loading indicators). + * + * @param filters - The {@link MutationFilters} to narrow down the matched mutations. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the mutations that your application is currently fetching. + * + * @example + * ```tsx + * import { useIsMutating } from '@tanstack/preact-query' + * + * // How many mutations are fetching? + * const isMutating = useIsMutating() + * // How many mutations matching the posts prefix are fetching? + * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + * ``` + */ export function useIsMutating( filters?: MutationFilters, queryClient?: QueryClient, @@ -60,6 +79,61 @@ function getResult< ) } +/** + * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass + * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation + * state. + * + * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the + * mutation state. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns Will be an Array of whatever `select` returns for each matching mutation. + * + * @example + * Get all variables of all running mutations: + * ```tsx + * import { useMutationState } from '@tanstack/preact-query' + * + * const variables = useMutationState({ + * filters: { status: 'pending' }, + * select: (mutation) => mutation.state.variables, + * }) + * ``` + * + * @example + * Get all data for specific mutations via the `mutationKey`: + * ```tsx + * import { useMutation, useMutationState } from '@tanstack/preact-query' + * + * const mutationKey = ['posts'] + * + * // Some mutation that we want to get the state for + * const mutation = useMutation({ + * mutationKey, + * mutationFn: createPosts, + * }) + * + * const data = useMutationState({ + * // this mutation key needs to match the mutation key of the given mutation (see above) + * filters: { mutationKey }, + * select: (mutation) => mutation.state.data, + * }) + * ``` + * + * @example + * Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the + * mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the + * latest invocation: + * ```tsx + * const data = useMutationState({ + * filters: { mutationKey: ['posts'] }, + * select: (mutation) => mutation.state.data, + * }) + * + * const latest = data[data.length - 1] + * ``` + */ export function useMutationState< TResult = MutationState, TMutation extends Mutation = diff --git a/packages/preact-query/src/usePrefetchInfiniteQuery.tsx b/packages/preact-query/src/usePrefetchInfiniteQuery.tsx index acfdc2bd32..33040037f8 100644 --- a/packages/preact-query/src/usePrefetchInfiniteQuery.tsx +++ b/packages/preact-query/src/usePrefetchInfiniteQuery.tsx @@ -4,6 +4,46 @@ import { useQueryClient } from './QueryClientProvider' import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core' import type { UsePrefetchInfiniteQueryOptions } from './types' +/** + * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, + * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass + * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless + * a default query function has been defined. + * + * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, + * as well as pageParam information, and should return a single variable that will be passed to your query + * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + * + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns `void` — nothing is returned. + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/preact-query' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchInfiniteQuery(projectsOptions) + * + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ export function usePrefetchInfiniteQuery< TQueryFnData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/usePrefetchQuery.tsx b/packages/preact-query/src/usePrefetchQuery.tsx index c0a237a55a..5c6e9772b9 100644 --- a/packages/preact-query/src/usePrefetchQuery.tsx +++ b/packages/preact-query/src/usePrefetchQuery.tsx @@ -4,6 +4,37 @@ import { useQueryClient } from './QueryClientProvider' import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core' import type { UsePrefetchQueryOptions } from './types' +/** + * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before + * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to + * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and + * `queryFn` is required unless a default query function has been defined. + * + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns `void` — nothing is returned. + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { usePrefetchQuery } from '@tanstack/preact-query' + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ export function usePrefetchQuery< TQueryFnData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/useQueries.ts b/packages/preact-query/src/useQueries.ts index dac252d010..b67b73988d 100644 --- a/packages/preact-query/src/useQueries.ts +++ b/packages/preact-query/src/useQueries.ts @@ -204,6 +204,56 @@ export type QueriesResults< > : { [K in keyof T]: GetUseQueryResult } +/** + * The `useQueries` hook can be used to fetch a variable number of queries. + * + * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the + * `queryClient` option - because the `QueryClient` can be passed in on the top level). + * + * Having the same query key more than once in the array of query objects may cause some data to be shared + * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired + * structure. + * + * The `combine` option can be used to combine the results of the queries into a single value. The result will + * be structurally shared to be as referentially stable as possible. + * + * @param queryClient - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context + * will be used. + * @returns The combined result. Without `combine`, this is an array with all the query results, in the same + * order as the input. When `combine` is provided, this is the value returned by `combine` instead. + * + * @example + * ```tsx + * import { useQueries } from '@tanstack/preact-query' + * + * const ids = [1, 2, 3] + * const results = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * staleTime: Infinity, + * })), + * }) + * ``` + * + * @example + * Combining results into a single value: + * ```tsx + * const ids = [1, 2, 3] + * const combinedQueries = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * combine: (results) => { + * return { + * data: results.map((result) => result.data), + * pending: results.some((result) => result.isPending), + * } + * }, + * }) + * ``` + */ export function useQueries< T extends Array, TCombinedResult = QueriesResults, @@ -212,10 +262,23 @@ export function useQueries< queries, ...options }: { + /** + * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and + * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and + * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` + * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + */ queries: | readonly [...QueriesOptions] | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] + /** + * 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. + */ combine?: (result: QueriesResults) => TCombinedResult + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. Defaults to `true`. + */ subscribed?: boolean }, queryClient?: QueryClient, diff --git a/packages/preact-query/src/useQuery.ts b/packages/preact-query/src/useQuery.ts index 2d6c5dcec1..2c59c79f95 100644 --- a/packages/preact-query/src/useQuery.ts +++ b/packages/preact-query/src/useQuery.ts @@ -12,6 +12,32 @@ import type { } from './types' import { useBaseQuery } from './useBaseQuery' +/** + * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`. + * + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result, typed so that `status` is `success` — or `error` if a fetch attempt + * fails while keeping the existing data (`status` never resolves to `pending` in this overload's type, + * since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience. + * + * @example + * ```tsx + * import { useQuery } from '@tanstack/preact-query' + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData`. + * const { data } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * return <>{data.map((post) =>

{post.title}

)} + * } + * ``` + */ export function useQuery< TQueryFnData = unknown, TError = DefaultError, @@ -22,6 +48,40 @@ export function useQuery< queryClient?: QueryClient, ): DefinedUseQueryResult +/** + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `pending` if there is no cached data and no query attempt + * has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to + * display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience. + * + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/preact-query' + * + * const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery(postsOptions) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ * {data.map((post) => ( + *

{post.title}

+ * ))} + *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + */ export function useQuery< TQueryFnData = unknown, TError = DefaultError, @@ -32,6 +92,77 @@ export function useQuery< queryClient?: QueryClient, ): UseQueryResult +/** + * @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `pending` if there is no cached data and no query attempt + * has finished yet, `error` if the query attempt resulted in an error, or `success` if the query has data to + * display. `isPending`/`isSuccess`/`isError` are derived booleans for convenience. + * + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/preact-query' + * + * const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery(postsOptions) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ * {data.map((post) => ( + *

{post.title}

+ * ))} + *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + * + * @example + * A dependent query, only enabled once `postId` is set: + * ```tsx + * import { useQuery } from '@tanstack/preact-query' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId!), + * enabled: postId != null, + * }) + * + * return

{data?.title}

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

{data?.title}

+ * } + * ``` + */ export function useQuery< TQueryFnData = unknown, TError = DefaultError, diff --git a/packages/preact-query/src/useSuspenseInfiniteQuery.ts b/packages/preact-query/src/useSuspenseInfiniteQuery.ts index 90a1c06d35..d09dc32551 100644 --- a/packages/preact-query/src/useSuspenseInfiniteQuery.ts +++ b/packages/preact-query/src/useSuspenseInfiniteQuery.ts @@ -15,6 +15,54 @@ import type { } from './types' import { useBaseQuery } from './useBaseQuery' +/** + * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`, + * `enabled`, and `placeholderData`. + * + * Caveat: cancellation does not work. + * + * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, + * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set + * accordingly). + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { useSuspenseInfiniteQuery } from '@tanstack/preact-query' + * + * function Projects() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, fetchNextPage, hasNextPage } = useSuspenseInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * return ( + *
+ * {data.pages.map((page) => + * page.projects.map((project) =>

{project.name}

), + * )} + * + *
+ * ) + * } + * + * function App() { + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ export function useSuspenseInfiniteQuery< TQueryFnData, TError = DefaultError, diff --git a/packages/preact-query/src/useSuspenseQueries.ts b/packages/preact-query/src/useSuspenseQueries.ts index 191c25458c..64b98fc855 100644 --- a/packages/preact-query/src/useSuspenseQueries.ts +++ b/packages/preact-query/src/useSuspenseQueries.ts @@ -162,25 +162,133 @@ export type SuspenseQueriesResults< > : { [K in keyof T]: GetUseSuspenseQueryResult } +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that each `query` can't have + * `throwOnError`, `enabled`, or `placeholderData`. + * + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context + * will be used. + * @returns 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. + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { useSuspenseQueries } from '@tanstack/preact-query' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const results = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {results.map((result) => ( + *
  • {result.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ export function useSuspenseQueries< T extends Array, TCombinedResult = SuspenseQueriesResults, >( options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ queries: | readonly [...SuspenseQueriesOptions] | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] + /** + * 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. + */ combine?: (result: SuspenseQueriesResults) => TCombinedResult }, queryClient?: QueryClient, ): TCombinedResult +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that each `query` can't have + * `throwOnError`, `enabled`, or `placeholderData`. + * + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context + * will be used. + * @returns 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. + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { useSuspenseQueries } from '@tanstack/preact-query' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const results = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {results.map((result) => ( + *
  • {result.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ export function useSuspenseQueries< T extends Array, TCombinedResult = SuspenseQueriesResults, >( options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ queries: readonly [...SuspenseQueriesOptions] + /** + * 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. + */ combine?: (result: SuspenseQueriesResults) => TCombinedResult }, queryClient?: QueryClient, diff --git a/packages/preact-query/src/useSuspenseQuery.ts b/packages/preact-query/src/useSuspenseQuery.ts index ad2ff4cca6..5e92d8aa35 100644 --- a/packages/preact-query/src/useSuspenseQuery.ts +++ b/packages/preact-query/src/useSuspenseQuery.ts @@ -5,6 +5,49 @@ import { defaultThrowOnError } from './suspense' import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' import { useBaseQuery } from './useBaseQuery' +/** + * The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and + * `placeholderData`. + * + * Caveat: cancellation does not work. + * + * @param options - The {@link UseSuspenseQueryOptions} to use — the same options as `useQuery`, minus the ones listed above. + * @param queryClient - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will + * be used. + * @returns 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). + * + * @example + * ```tsx + * import { Suspense } from 'preact/compat' + * import { useSuspenseQuery } from '@tanstack/preact-query' + * + * function Posts() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, isFetching } = useSuspenseQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + *
+ *

Posts {isFetching ? : null}

+ * {data.map((post) => ( + *

{post.title}

+ * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ export function useSuspenseQuery< TQueryFnData = unknown, TError = DefaultError,