Skip to main content
Version: 2.x

useInfiniteQuery(...)

The Hook enables you to perform asynchronous data fetching operations with support for infinite scrolling scenarios. See the TanStack useInfiniteQuery(...) 🌴 documentation for more details.

const query = api.<service>.<operation>.useInfiniteQuery(
parameters,
infiniteQueryOptions
)

Arguments

  1. parameters: { path, query, header } | QueryKey | undefined

    • Required only if OpenAPI specification defines required parameters
    • If the operation has no required parameters according to OpenAPI, you can omit this argument
    • parameters will be used to generate the QueryKey
    • Instead of an object with {path, query, header}, you can pass a QueryKey as an array which is also strictly-typed ✨
    • If operation does not require parameters, you must pass an empty object {} for strictness
  2. infiniteQueryOptions?: UseInfiniteQueryOptions

    • Optional, represents the options of the useInfiniteQuery(...) 🌴 Hook
      • queryOptions.queryFn could be provided to override the default queryFn used by Qraft

Returns

UseInfiniteQueryResult object, see the TanStack useInfiniteQuery(...) 🌴 documentation for more details.

Examples

tip

By default, useInfiniteQuery hooks are only generated for read operations (GET method). If you want to use query hooks for write operations (POST, PUT, PATCH methods), use the --queryable-write-operations CLI option during code generation.

src/PostList.tsx
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI

import { requestFn } from '@openapi-qraft/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

const api = createAPIClient({
requestFn,
queryClient,
baseUrl: 'https://my-blog.com/api',
});

function PostList() {
/**
* `api.posts.getPosts.useInfiniteQuery(...)` launches
* the initial query to fetch the first page of posts:
* ###
* GET /posts?limit=10&page=1
*/
const infiniteQuery = api.posts.getPosts.useInfiniteQuery(
{ query: { limit: 10 } },
{
getNextPageParam: (lastPage, allPages, lastPageParams) => {
if (lastPage.length < 10) return; // if less than 10 items, there are no more pages
return {
query: {
page: Number(lastPageParams.query?.page) + 1,
},
};
},
initialPageParam: {
query: {
page: 1, // will be used in initial request
},
},
}
);

return (
<div>
{infiniteQuery.data?.pages.map((page, pageIndex) => (
<ul key={pageIndex}>
{page.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
))}
<button onClick={() => {
// ⬇︎ Initiates a GET request for the next page of posts: /posts?limit=10&page=2
infiniteQuery.fetchNextPage()
}}>
Load More
</button>
</div>
);
}

export default function App() {
return (
<QueryClientProvider client={queryClient}>
<PostList />
</QueryClientProvider>
);
}