Chat history
A chat channel with the newest message at the bottom. Scroll up and older messages load above, while the message you were reading stays where it was. The messages are dummyjson comments.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { getMessageCountRequest, pageSize } from "./api";
import { ChatHistory } from "./ChatHistory";
export const App = () => {
// The chat opens at the newest page, so the total decides where to start.
const { data, error, loading } = useFetch(getMessageCountRequest);
return (
<main className="container narrow">
<hgroup>
<h1>Chat history</h1>
<p>The newest messages are at the bottom. Scroll up to load older ones. Your place in the chat stays put.</p>
</hgroup>
{loading && !data && <p aria-busy="true">Opening the conversation...</p>}
{error && <p className="error">Could not open the conversation: {error.message}</p>}
{data && <ChatHistory startAt={Math.max(data.total - pageSize, 0)} />}
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/chat-history hyper-fetch-react-chat-history && cd hyper-fetch-react-chat-history && npm install && npm run dev- Start at the end:
useInfiniteFetchstarts at the last page by settingskipon the request. fetchPreviousPageloads the page before the first loaded one when you get near the top.- Scroll position: a layout effect keeps the same distance from the bottom after older messages are added.
uniqueBy: "id"removes messages repeated by overlapping pages.
How it works
-
dummyjson lists comments from the oldest.
App.tsxfirst asks for the total withgetMessageCountRequest(one item, only theidfield) and rendersChatHistorywithstartAt = total - pageSize. -
ChatHistorypasses that offset as the startingskip. Withoffset: "skip"pagination, the first loaded page is the newest one,hasNextPageisfalseandhasPreviousPageistrue:useInfiniteFetch(// `select` is a dummyjson query param: the API returns only these fields.getMessagesRequest.setQueryParams({ limit: pageSize, skip: startAt, select: "body,user" }),{ pagination: messagesPagination, uniqueBy: "id" },); -
The scroll handler stores the distance from the bottom and calls
fetchPreviousPage()when the top is less than 120 pixels away. Calls made while a page is loading share one request. -
When the first page param changes,
useLayoutEffectsetsscrollTopso the distance from the bottom is the same as before. It runs before the browser paints, so the messages do not jump. On the first page that distance is 0, so the chat opens at the newest message.overflow-anchor: nonestops the browser from adjusting the scroll a second time. -
Near the start, the offset cannot go below 0. If the total is not a multiple of the page size, the first page overlaps the second, and
uniqueBy: "id"drops the repeated messages. -
A failed page shows a Try again button that calls
fetchPreviousPage()again.
- Chats, comment threads, activity logs and any list read from the bottom up.
- If your API returns the newest messages first with a "before" cursor, use cursor pagination instead: older messages
are then the next page (
fetchNextPage), and you reverseitemsfor display.
Related
The list starts at the newest page and fetchPreviousPage walks back in time. Keeping the distance from the bottom in a
layout effect holds your place while older messages are added above.
