Skip to main content

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.

advanceduseInfiniteFetchpaginationuseFetch
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/chat-history hyper-fetch-react-chat-history && cd hyper-fetch-react-chat-history && npm install && npm run dev
What it shows
  1. Start at the end: useInfiniteFetch starts at the last page by setting skip on the request.
  2. fetchPreviousPage loads the page before the first loaded one when you get near the top.
  3. Scroll position: a layout effect keeps the same distance from the bottom after older messages are added.
  4. uniqueBy: "id" removes messages repeated by overlapping pages.

How it works​

  1. dummyjson lists comments from the oldest. App.tsx first asks for the total with getMessageCountRequest (one item, only the id field) and renders ChatHistory with startAt = total - pageSize.

  2. ChatHistory passes that offset as the starting skip. With offset: "skip" pagination, the first loaded page is the newest one, hasNextPage is false and hasPreviousPage is true:

    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" },
    );
  3. 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.

  4. When the first page param changes, useLayoutEffect sets scrollTop so 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: none stops the browser from adjusting the scroll a second time.

  5. 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.

  6. A failed page shows a Try again button that calls fetchPreviousPage() again.

When to use it
  • 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 reverse items for display.

Summary

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.