Skip to the code

A journal that loads more as you scroll

The Leaf and Kettle journal, /journal, lists its posts newest first. Its page, a Server Component, loads the first four with getPosts(null) from @/lib/journal and renders JournalFeed with them. Write the feed, app/journal/journal-feed.tsx, a Client Component whose default export is JournalFeed({ initialPosts, initialCursor }), so that more posts load by themselves as the reader reaches the bottom.

Show the posts in a list, an item with each post's title. While there are more posts (the cursor, initialCursor at first, isn't null), put one element after the list and watch it with an IntersectionObserver. When it comes into view, load the next page with loadMorePosts(cursor), the Server Action in ./actions, which answers { posts, nextCursor }: add its posts to the end of the list and keep its nextCursor for the next load.

While a page loads, show Loading more posts…. Load one page at a time: the observer can fire again before a load has finished, and that must not start a second one. An entry that isn't intersecting loads nothing.

When the cursor is null, watch nothing any more and show You've read every post. in place of the watched element.

If loadMorePosts throws, show Couldn't load more posts. in an element with role="alert", and a Try again button that loads the same page again.

first render     4 posts, and one element after them, watched
scroll to it     Loading more posts…  → loadMorePosts("p8") → 8 posts
and again        loadMorePosts("p4") → 11 posts, nextCursor null
                 You've read every post.   (nothing watched)

The app's other files

lib/journal.ts, read-only. Import it as @/lib/journal.

export type Post = { id: string; title: string };
 
/** Every journal post, newest first: a stand-in for the shop's database. */
export const posts: Post[] = [
  { id: "p11", title: "Cold-brewing sencha" },
  { id: "p10", title: "Why oolong likes short steeps" },
  { id: "p9", title: "A morning in a Darjeeling garden" },
  { id: "p8", title: "Matcha without a whisk" },
  { id: "p7", title: "The story of Earl Grey" },
  { id: "p6", title: "Choosing your first teapot" },
  { id: "p5", title: "Rooibos for the evening" },
  { id: "p4", title: "Water temperature, simply" },
  { id: "p3", title: "Our first tasting night" },
  { id: "p2", title: "Keeping tea fresh at home" },
  { id: "p1", title: "Hello from Leaf and Kettle" },
];
 
/** How many posts a page has. */
export const PAGE_SIZE = 4;
 
/** The database as the feed's Server Action sees it: every cursor it was asked for, and whether it's down. */
export const feed = { requests: [] as string[], down: false };
 
/**
 * A page of posts: the first PAGE_SIZE when `cursor` is null, or the PAGE_SIZE after the post whose id is
 * `cursor`. `nextCursor` is the id of the page's last post, or null when no posts come after it.
 */
export async function getPosts(cursor: string | null): Promise<{ posts: Post[]; nextCursor: string | null }> {
  const start = cursor === null ? 0 : posts.findIndex((post) => post.id === cursor) + 1;
  if (cursor !== null && start === 0) return { posts: [], nextCursor: null };
  const page = posts.slice(start, start + PAGE_SIZE).map((post) => ({ ...post }));
  const more = start + PAGE_SIZE < posts.length;
  return { posts: page, nextCursor: more ? page[page.length - 1].id : null };
}

app/journal/actions.ts, read-only. Import it as @/app/journal/actions.

"use server";
 
import { feed, getPosts } from "@/lib/journal";
 
/** How long the database takes to answer. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
/**
 * The page of posts after `cursor`, the id of the last post the feed shows, and the cursor for the
 * page after it (null at the end). Takes 300 ms, and throws when the database is down.
 */
export async function loadMorePosts(cursor: string) {
  feed.requests.push(cursor);
  await wait(300);
  if (feed.down) throw new Error("The journal's database didn't answer.");
  return getPosts(cursor);
}

app/journal/page.tsx, read-only. Import it as @/app/journal/page.

import { getPosts } from "@/lib/journal";
import JournalFeed from "./journal-feed";
 
export default async function JournalPage() {
  const { posts, nextCursor } = await getPosts(null);
 
  return (
    <main>
      <h1>The Leaf and Kettle journal</h1>
      <JournalFeed initialPosts={posts} initialCursor={nextCursor} />
    </main>
  );
}

What the tests check

  1. is a Client Component the journal page renders with its first posts
    const renderOnServer = async (element, options) => {
      try {
        return await renderServer(element, options);
      } catch (error) {
        if (/reading 'use[A-Za-z]*'/.test(String(error && error.message))) {
          throw new Error('A component that calls hooks ran as a Server Component, where there are none. Does its file start with "use client"? (' + error.message + ")");
        }
        throw error;
      }
    };
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderOnServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "The Leaf and Kettle journal" })).toBeInTheDocument();
    expect(titles()).toEqual(firstPage);
    expect(feed.requests).toEqual([]);
    
  2. loads the next posts when the end of the list comes into view
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderServer(<Page />);
    await scrollToEnd();
    expect(screen.getByText("Loading more posts…")).toBeInTheDocument();
    expect(feed.requests).toEqual(["p8"]);
    await clock.advance(300);
    expect(titles()).toEqual([...firstPage, ...secondPage]);
    expect(screen.queryByText("Loading more posts…")).not.toBeInTheDocument();
    
  3. each load starts after the last post shown
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderServer(<Page />);
    await scrollToEnd();
    await clock.advance(300);
    await scrollToEnd();
    expect(feed.requests).toEqual(["p8", "p4"]);
    await clock.advance(300);
    expect(titles()).toEqual([...firstPage, ...secondPage, ...lastPage]);
    
  4. loads one page at a time, and only when the end is in view
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderServer(<Page />);
    const end = watched();
    await observer.trigger(end, false);
    expect(feed.requests).toEqual([]);
    await observer.trigger(end);
    await observer.trigger(end);
    expect(feed.requests).toEqual(["p8"]);
    await clock.advance(300);
    expect(titles()).toEqual([...firstPage, ...secondPage]);
    
  5. stops at the end: says so, and watches nothing
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderServer(<Page />);
    await scrollToEnd();
    await clock.advance(300);
    await scrollToEnd();
    await clock.advance(300);
    expect(screen.getByText("You've read every post.")).toBeInTheDocument();
    expect(observer.observed()).toEqual([]);
    expect(feed.requests).toEqual(["p8", "p4"]);
    cleanup();
    render(<JournalFeed initialPosts={[{ id: "p1", title: "Hello from Leaf and Kettle" }]} initialCursor={null} />);
    expect(screen.getByText("You've read every post.")).toBeInTheDocument();
    expect(observer.observed()).toEqual([]);
    
  6. a failed load says so, and Try again loads the same page
    const titles = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const observer = mockIntersectionObserver();
    const clock = useFakeTimers();
    // The one element the feed watches, below its list.
    const watched = () => {
      const elements = observer.observed();
      if (elements.length !== 1) throw new Error("The feed should watch one element, but it watches " + elements.length + ".");
      return elements[0];
    };
    const scrollToEnd = () => observer.trigger(watched());
    const firstPage = ["Cold-brewing sencha", "Why oolong likes short steeps", "A morning in a Darjeeling garden", "Matcha without a whisk"];
    const secondPage = ["The story of Earl Grey", "Choosing your first teapot", "Rooibos for the evening", "Water temperature, simply"];
    const lastPage = ["Our first tasting night", "Keeping tea fresh at home", "Hello from Leaf and Kettle"];
    await renderServer(<Page />);
    feed.down = true;
    await scrollToEnd();
    await clock.advance(300);
    expect(screen.getByRole("alert")).toHaveTextContent("Couldn't load more posts.");
    expect(screen.queryByText("Loading more posts…")).not.toBeInTheDocument();
    expect(titles()).toEqual(firstPage);
    feed.down = false;
    await user.click(screen.getByRole("button", { name: "Try again" }));
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    await clock.advance(300);
    expect(titles()).toEqual([...firstPage, ...secondPage]);
    expect(feed.requests).toEqual(["p8", "p8"]);
    

Learn more

app/journal/journal-feed.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).