Skip to content

Pagination: frontend and iteration

Iterating everything — pages() / items()

Section titled “Iterating everything — pages() / items()”

Every paginator exposes lazy async generators that auto-walk the pagination for exports, migrations, syncs:

// page by page — one fetch per loop turn; breaking stops fetching
for await (const page of paginator.pages({ type: "cursor", limit: 500 })) {
await writeBatch(page.items);
}
// flattened items
for await (const user of paginator.items({ type: "offset", limit: 100, offset: 0 })) {
await reindex(user);
}
// composes with the iterable utils
const all = await collect(paginator.items({ type: "cursor", limit: 100 }));
for await (const [i, row] of enumerate(paginator.items({ type: "cursor", limit: 100 }))) { ... }
  • Cursor inputs follow endCursor until hasNextPage is false (or startCursor/hasPreviousPage with direction: "backward" — an “everything newer than X” iterator).
  • Page/offset inputs advance the offset by the items actually returned, so you can start mid-set. Internally, pages() rewrites subsequent requests to { type: "offset", limit, offset: prevOffset + items.length } — the original page input shape is not preserved across iterations.
  • Two guard rails stop infinite loops from misbehaving fetchers: an empty page ends iteration, and so does a cursor that didn’t advance.
  • Always AsyncGenerator (even on a sync paginator) — for await handles sync pages transparently.

The loop pages() runs:

flowchart TD
  START["pages(input)"] --> FETCH["paginate(current)"]
  FETCH --> YIELD["yield page"]
  YIELD --> EMPTY{"items empty?"}
  EMPTY -->|yes| STOP(["done"])
  EMPTY -->|no| TYPE{"input type"}
  TYPE -->|cursor| MORE{"more in this direction<br/>and the cursor advanced?"}
  MORE -->|no| STOP
  MORE -->|yes| NEXTC["cursor = endCursor<br/>(startCursor if backward)"]
  TYPE -->|"page / offset"| HN{"hasNextPage?"}
  HN -->|no| STOP
  HN -->|yes| NEXTO["offset += items.length"]
  NEXTC --> FETCH
  NEXTO --> FETCH

TanStack Query infinite scroll — infinitePaginationOptions

Section titled “TanStack Query infinite scroll — infinitePaginationOptions”

A plain-object factory (no dependency on @tanstack/react-query, so it lives in the zero-dep core and works with the React, Vue, Solid, and Svelte adapters alike):

import { useInfiniteQuery } from "@tanstack/react-query";
import { createPaginator, infinitePaginationOptions } from "@xtandard/lib/pagination";
// client-side paginator that calls your API
const apiPaginator = createPaginator({
fetchCursor: async ({ limit, cursor }) => {
const url = new URL("/api/posts", location.origin);
url.searchParams.set("limit", String(limit));
if (cursor) url.searchParams.set("cursor", cursor.token);
const { data, meta } = await (await fetch(url)).json();
return { items: data };
},
cursor: { fromItem: (post) => ({ token: post.id }) },
});
function Feed() {
const { data, fetchNextPage, fetchPreviousPage, hasNextPage } = useInfiniteQuery({
queryKey: ["posts"],
...infinitePaginationOptions(apiPaginator, { pageSize: 20 }),
});
// data.pages: Paginated<Post>[] — fetchPreviousPage works too (bidirectional)
}

Constraints:

  • Requires a cursor-capable paginator (fetchCursor + cursor config). Offset-only paginators won’t work — TanStack infinite queries walk cursors.
  • Only pageSize is configurable (maps to limit); initial param is always null (first page).
  • queryFn always issues { type: "cursor", ... } regardless of how your REST API names params — map in fetchCursor.

getNextPageParam/getPreviousPageParam are wired from pageInfo.endCursor/startCursor, and the direction TanStack passes maps onto backward fetches — so a both-ways feed (scroll down for older, scroll up for newer) is the default behavior, not extra work.

flowchart LR
  Q["useInfiniteQuery"] -->|"pageParam (null first)<br/>+ direction"| FN["queryFn"]
  FN -->|"{ type: cursor, limit: pageSize,<br/>cursor, direction }"| P["paginator.paginate"]
  P --> PG["Paginated page"]
  PG -->|"getNextPageParam:<br/>endCursor if hasNextPage"| Q
  PG -->|"getPreviousPageParam:<br/>startCursor if hasPreviousPage"| Q

Often the simpler client-side shape is: let the server own the paginator and just forward meta.endCursor as the next request’s ?cursor=. The client never needs this library for that — the tokens are plain strings.

Have your fetcher report totalItems and drive a pager from the envelope:

const { items, pageInfo } = await paginator.paginate({ type: "page", page, pageSize: 25 });
// pageInfo: { page: 3, pageSize: 25, totalItems: 612, totalPages: 25, hasNextPage: true, ... }
<Pager
page={pageInfo.page}
totalPages={pageInfo.totalPages}
onNext={() => setPage(page + 1)}
disabled={{ next: !pageInfo.hasNextPage, prev: !pageInfo.hasPreviousPage }}
/>;

Local data (search results, client-side tables)

Section titled “Local data (search results, client-side tables)”

The all-sync tier means client-side pagination of an in-memory list needs no effects, no suspense, no loading states:

import { applyFiltersToArray, createMemoryPaginator } from "@xtandard/lib/filters/memory";
const paginator = useMemo(
() =>
createMemoryPaginator({
rows: applyFiltersToArray(rows, { spec, filters }),
sort: [{ key: sortField, order: sortDir }, { key: "id" }],
}),
[rows, filters, sortField, sortDir],
);
const { items, pageInfo } = paginator.paginate({ type: "page", page, pageSize: 10 }); // sync, in render