alepha@docs:~/docs/.content/release/framework/docs/reference/react-hooks$
cat useInfiniteQuery.md | pretty
1 min read
Last commit:

#useInfiniteQuery

#Import

typescript
1import { useInfiniteQuery } from "alepha/react";

#Overview

Hook for a list read page by page, every page loaded so far kept under one cache key: a "load more" button, an infinite scroll.

Built over useQuery: the entry under key is an InfiniteQueryData, { pages, pageParams }, so dedupe, staleTime, invalidates, retries, the reconnect and tab-return refetches and eviction apply to it with no second code path.

One mechanism: handler(ctx, pageParam) reads one page, initialPageParam is the first page's param, and getNextPageParam(lastPage, pages) returns the next one, or undefined at the end. Offset and cursor are two uses of it.

#Examples

By page, on a Page<T> from paginate()

tsx
 1const { pages, loadMore, hasMore, loadingMore } = useInfiniteQuery( 2  { 3    key: ["orders", userId], 4    handler: ({ signal }, page: number) => 5      orderApi.list({ query: { page, size: 20 } }, { request: { signal } }), 6    initialPageParam: 0, 7    getNextPageParam: (last) => 8      last.page.isLast ? undefined : last.page.number + 1, 9  },10  [userId],11);12const rows = pages.flatMap((page) => page.content);

By cursor

tsx
 1useInfiniteQuery( 2  { 3    key: ["inbox"], 4    handler: (_ctx, cursor: string | undefined) => 5      inboxApi.list({ query: { cursor } }), 6    initialPageParam: undefined, 7    getNextPageParam: (last) => last.nextCursor, 8  }, 9  [],10);

A refetch reloads what is loaded. After an invalidation, refetch(), a reconnect or a tab-return refetch, the pages loaded so far are read again in order, each param taken from the fresh previous page, stopping early if the list got shorter, and the entry is written once at the end. A list with 20 pages loaded sends 20 requests each time. A key change starts again from the first page.

An optimistic write needs no helper: useQueryClient().setData(key, (data: InfiniteQueryData<Page, Param>) => ({ ...data, pages: data.pages.map(...) })).