Rest Pagination
Expanding Lists
To append results to the list instead of moving to another page, use Resource.getList.getPage. It needs paginationField.
import { useController, useLoading } from '@data-client/react'; import { PostResource } from './Post'; export default function LoadMore({ cursor }: { cursor: string }) { const ctrl = useController(); const [loadPage, isPending] = useLoading( () => ctrl.fetch(PostResource.getList.getPage, { cursor }), [cursor], ); return ( <div className="loadMore"> <button onClick={loadPage} disabled={isPending}> {isPending ? '...' : 'Load more'} </button> </div> ); }
Set the Resource's paginationField and schema:
export const PostResource = resource({
path: '/posts/:id',
schema: Post,
paginationField: 'cursor',
}).extend('getList', {
schema: { posts: new Collection([Post]), cursor: '' },
});
Github Issues Demo
NextPage calls RestEndpoint.getPage on click. Scroll to the bottom of the preview
and click "Load more" to append the next page of issues.
Explore the github-app example
Using RestEndpoint Directly
This example uses the Cosmos Hub validators list. It has only one endpoint, so it uses RestEndpoint instead of resource. With a Collection and paginationField, RestEndpoint.getPage appends the next page of validators to the list.
import { useController, useLoading } from '@data-client/react'; import { getValidators } from './Validator'; export default function LoadMore({ next_key, limit }) { const ctrl = useController(); const [handleLoadMore, isPending] = useLoading( () => ctrl.fetch(getValidators.getPage, { 'pagination.limit': limit, 'pagination.key': next_key, }), [next_key, limit], ); if (!next_key) return null; return ( <div className="loadMore"> <button onClick={handleLoadMore} disabled={isPending}> {isPending ? '...' : 'Load more'} </button> </div> ); }
Page numbers in an envelope
Many APIs wrap each list in an envelope: an outer object that holds the data next to metadata, like
{ "data": [...], "meta": { "page": 1, "totalPages": 4 } }. Make the envelope the schema, with the
Collection at data, so components can read meta too:
import { Collection, Entity, RestEndpoint } from '@data-client/rest';
export class Comment extends Entity {
id = '';
body = '';
}
export const getComments = new RestEndpoint({
path: '/comments',
searchParams: {} as { discussionId: string; page?: number },
paginationField: 'page',
schema: {
data: new Collection([Comment]),
meta: { page: 0, totalPages: 0 },
},
});
import { useController, useSuspense } from '@data-client/react';
import { getComments } from './Comment';
function CommentList({ discussionId }: { discussionId: string }) {
const { data, meta } = useSuspense(getComments, { discussionId });
const ctrl = useController();
const loadMore = () =>
ctrl.fetch(getComments.getPage, { discussionId, page: meta.page + 1 });
const add = (body: string) =>
ctrl.fetch(getComments.push, { discussionId }, { body });
// render data, a "Load more" button while meta.page < meta.totalPages, and a form calling add()
}
- The first fetch leaves out
page: getPage finds the list to extend by its args without the paginationField, so a list fetched withpage: 1is a different one that never grows. - Each page appends to
dataand replacesmeta, sometaalways describes the latest page. - push sends a
POSTto the same path and adds the oneCommentit returns. A separate create endpoint joins the same list withschema: getComments.schema.data.push, called with{ discussionId }.
Infinite Scrolling
Infinite scroll UI differs by app and platform (React Native or web). This example uses a Pagination component that
calls a callback to fetch the next page. On the web, build it with an
Intersection Observer.
import { useSuspense, useController } from '@data-client/react';
import { PostResource } from 'resources/Post';
import Pagination from './Pagination';
import PostList from './PostList';
function NewsList() {
const { results, cursor } = useSuspense(PostResource.getList);
const ctrl = useController();
return (
<Pagination
onPaginate={() =>
ctrl.fetch(PostResource.getList.getPage, { cursor })
}
>
<PostList posts={results} />
</Pagination>
);
}
Tokens in HTTP Headers
Some APIs send pagination tokens in HTTP headers instead of the body. Override
getList's parseResponse() to add the header to
the response. In this example, the token is in the link header. The rest of the example above stays the same.
import { resource } from '@data-client/rest';
export const ArticleResource = resource({
path: '/articles/:id',
schema: Article,
}).extend(Base => ({
getList: Base.getList.extend({
schema: { results: [Article], link: '' },
async parseResponse(response: Response) {
const results = await Base.getList.parseResponse(response);
if (
(response.headers && response.headers.has('link')) ||
Array.isArray(results)
) {
return {
link: response.headers.get('link'),
results,
};
}
return results;
},
}),
}));
Code organization
If many endpoints share the same pagination, put the logic in a custom Endpoint class.
import { Collection, RestEndpoint, type RestGenerics } from '@data-client/rest';
export class PagingEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async parseResponse(response: Response) {
const results = await super.parseResponse(response);
if (
(response.headers && response.headers.has('link')) ||
Array.isArray(results)
) {
return {
link: response.headers.get('link'),
results,
};
}
return results;
}
}
import { Collection, Entity, resource } from '@data-client/rest';
import { PagingEndpoint } from './PagingEndpoint';
export const MyResource = resource({
path: '/stuff/:id',
schema: MyEntity,
Endpoint: PagingEndpoint,
});