Load more
A post list that opens on page five, as if from a shared link. "Load more" adds the next page, "Load earlier posts" adds the one before, and every page is drawn as its own box so you can see how the responses join into one list.
intermediateuseInfiniteFetchpagination
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useInfiniteFetch } from "@hyper-fetch/react";
import { getPosts, postsPagination } from "./api";
const PAGE_SIZE = 5;
export const App = () => {
const {
items,
pages,
pageParams,
total,
loading,
error,
isFetching,
hasNextPage,
hasPreviousPage,
isFetchingNextPage,
isFetchingPreviousPage,
fetchNextPage,
fetchPreviousPage,
refetch,
reset,
} = useInfiniteFetch(
// `skip: 20` starts the list in the middle, as if the user opened a shared link to the fifth page.
// `select` is a dummyjson query param: the API returns only these fields.
getPosts.setQueryParams({ limit: PAGE_SIZE, skip: 20, select: "title,views" }),
{ pagination: postsPagination },
);
if (loading) return <main className="container" aria-busy="true" />;
if (error && items.length === 0) {
return (
<main className="container">
<p>Could not load posts: {error.message}</p>
</main>
);
}
return (
<main className="container">
<hgroup>
<h1>Posts</h1>
<p>
{items.length} of {total} posts in {pages.length} {pages.length === 1 ? "page" : "pages"}. Each box below is
one response from the server.
</p>
</hgroup>
<div className="toolbar">
<button type="button" className="outline secondary" onClick={() => refetch()} disabled={isFetching}>
Reload all pages
</button>
<button type="button" className="outline secondary" onClick={() => reset()} disabled={isFetching}>
Start over
</button>
</div>
{hasPreviousPage && (
<button
type="button"
className="outline wide"
onClick={() => fetchPreviousPage()}
aria-busy={isFetchingPreviousPage}
disabled={isFetchingPreviousPage}
>
Load earlier posts
</button>
)}
{/* `pages` keeps the page boundaries. `items` is the same posts as one flat list. */}
{pages.map((page, index) => (
<article key={String(pageParams[index])} className="page">
<header>
<small className="muted">
Page {Number(pageParams[index]) / PAGE_SIZE + 1} · skip={String(pageParams[index])} · {page.posts.length}{" "}
posts
</small>
</header>
<ol start={Number(pageParams[index]) + 1}>
{page.posts.map((post) => (
<li key={post.id}>
{post.title} <small className="muted">{post.views} views</small>
</li>
))}
</ol>
</article>
))}
{hasNextPage ? (
<button
type="button"
className="wide"
onClick={() => fetchNextPage()}
aria-busy={isFetchingNextPage}
disabled={isFetchingNextPage}
>
Load more
</button>
) : (
<p className="muted">That is every post.</p>
)}
{error && <p>Could not load the page: {error.message}</p>}
</main>
);
};
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/load-more hyper-fetch-react-load-more && cd hyper-fetch-react-load-more && npm install && npm run devWhat it shows
- Buttons instead of scrolling.
fetchNextPage()andfetchPreviousPage()are plain functions you call from any event. - Starting in the middle. The
skipset on the request is the first page, andhasPreviousPageistrue. - Page boundaries.
pagesandpageParamskeep each response and its offset,itemsis the flat list. - Reloading and starting over.
refetch()reloads every loaded page,reset()goes back to the starting page.
How it works
api.tsdeclarespostsPaginationwithoffset: "skip",limit: "limit",items: "posts"andtotal: "total", checked withsatisfies Pagination<typeof getPosts>.ApppassesgetPosts.setQueryParams({ limit: 5, skip: 20, ... }). The list starts from the value already on the request, so the first response is posts 21-25.- "Load more" calls
fetchNextPage(), which sendsskip=25. "Load earlier posts" callsfetchPreviousPage(), which sendsskip=15and adds the page at the top.isFetchingNextPageandisFetchingPreviousPagedrive each button's busy state. - The list is drawn from
pages, withpageParams[index]as the page label. The same posts are also initems, which the header uses to count them. refetch()sends all loaded pages again in parallel and swaps them when they arrive.reset()drops back toskip=20and fetches it again.hasNextPageturnsfalseonceskip + limitreachestotal, and the button is replaced by an end message.
const { pages, pageParams, hasNextPage, fetchNextPage } = useInfiniteFetch(request, { pagination: postsPagination });
const loadMore = () => fetchNextPage();
When to use it
- Lists where users decide when to load more, such as comments or activity logs.
- Pages opened at a deep offset, for example from a link, that should still let users go back.
- For loading on scroll, see Infinite scroll.
Related
Summary
You loaded pages in both directions with buttons, rendered the page boundaries from pages and pageParams, and used
refetch() and reset() to reload or restart the list.
