Skip to the code

Comments that appear before the server answers

Each post in the Leaf and Kettle journal ends with its comments. The post's page, a Server Component, renders Comments with the post's slug, its comments from getComments(slug) in @/lib/comments, oldest first, and the signed-in customer's name. Write app/journal/[slug]/comments.tsx, a Client Component whose default export is Comments({ postSlug, comments, viewerName }), in which a new comment shows the moment it's posted.

Show an <h2> with the count, Comments (2), then a list with an item like Kenji: Tried it overnight. So smooth. for each comment (no list when there are none), then a form: a textarea labelled Your comment and a Post button.

Posting calls postComment(postSlug, text), the Server Action in ../actions, with the text trimmed; a blank comment sends nothing. Saving takes half a second, so straight away, using React's useOptimistic: add the comment to the list by viewerName, followed by (sending…), count it in the heading, empty the textarea, and disable Post until the answer comes, so comments go one at a time.

postComment answers { ok: true, comment } once it has saved the comment, and calls revalidatePath for the post's page, so Next.js sends the page's fresh comments, with the new one in them, in the same response: the list then shows it once, without (sending…). It answers { ok: false, error } when it refuses the comment, and the call throws when the connection drops. Either way, take the comment out of the list, put what the customer typed back in the textarea, and show the error, or Couldn't post your comment. Check your connection and try again., in an element with role="alert". Posting again clears the message.

Comments (2)
  Kenji: Tried it overnight. So smooth.
  Mei: Works with genmaicha too!
Your comment [Lovely with lemon]  [Post]
 
Post → at once:  Comments (3), Ana: Lovely with lemon (sending…), empty textarea, Post disabled
       500 ms:   the page's fresh comments: Ana: Lovely with lemon
       refused:  Comments (2), "Lovely with lemon" back in the textarea, the error (role="alert")

The app's other files

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

export type Comment = { id: string; author: string; text: string };
 
const posts = [{ slug: "cold-brew-sencha", title: "Cold-brewing sencha" }];
 
/** Each post's comments, oldest first: a stand-in for the shop's database. */
export const comments: Record<string, Comment[]> = {
  "cold-brew-sencha": [
    { id: "c1", author: "Kenji", text: "Tried it overnight. So smooth." },
    { id: "c2", author: "Mei", text: "Works with genmaicha too!" },
  ],
};
 
/** Every comment sent to the server, as it arrived. */
export const sent: { postSlug: string; text: string }[] = [];
 
/** Set `closed` and the server refuses new comments. Set `offline` and the call fails without an answer. */
export const commentsService = { closed: false, offline: false };
 
/** The post with this slug, or undefined when there's none. */
export async function getPost(slug: string) {
  return posts.find((post) => post.slug === slug);
}
 
/** The post's comments, oldest first. */
export async function getComments(postSlug: string): Promise<Comment[]> {
  return (comments[postSlug] ?? []).map((comment) => ({ ...comment }));
}
 
/** The signed-in customer: a stand-in for reading the session. */
export async function getViewer() {
  return { name: "Ana" };
}

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

"use server";
 
import { revalidatePath } from "next/cache";
import { comments, commentsService, sent, type Comment } from "@/lib/comments";
 
export type PostCommentResult = { ok: true; comment: Comment } | { ok: false; error: string };
 
let count = 0;
 
/** How long the database takes to save. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
/**
 * Saves a comment on the post by the signed-in customer, then revalidates the post's page. Takes
 * 500 ms. Answers the saved comment, or why it was refused; throws when the connection drops.
 */
export async function postComment(postSlug: string, text: string): Promise<PostCommentResult> {
  sent.push({ postSlug, text });
  await wait(500);
  if (commentsService.offline) throw new TypeError("Failed to fetch");
  const clean = String(text ?? "").trim();
  if (!clean || clean.length > 280) return { ok: false, error: "Write a comment of up to 280 characters." };
  if (commentsService.closed) return { ok: false, error: "Comments are closed for a few minutes. Try again soon." };
  count += 1;
  const comment = { id: `n${count}`, author: "Ana", text: clean };
  (comments[postSlug] ??= []).push(comment);
  revalidatePath(`/journal/${postSlug}`);
  return { ok: true, comment: { ...comment } };
}

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

import { notFound } from "next/navigation";
import { getComments, getPost, getViewer } from "@/lib/comments";
import Comments from "./comments";
 
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  const [comments, viewer] = await Promise.all([getComments(slug), getViewer()]);
 
  return (
    <main>
      <h1>{post.title}</h1>
      <Comments postSlug={post.slug} comments={comments} viewerName={viewer.name} />
    </main>
  );
}

What the tests check

  1. is a Client Component the post's page shows with its comments
    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;
      }
    };
    await renderOnServer(<Page params={params({ slug: "cold-brew-sencha" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Cold-brewing sencha" })).toBeInTheDocument();
    expect(screen.getByRole("heading", { level: 2, name: "Comments (2)" })).toBeInTheDocument();
    expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["Kenji: Tried it overnight. So smooth.", "Mei: Works with genmaicha too!"]);
    expect(screen.getByLabelText("Your comment")).toHaveValue("");
    expect(screen.getByRole("button", { name: "Post" })).toBeEnabled();
    
  2. shows the comment at once, marked as sending
    const clock = useFakeTimers();
    const SLUG = "cold-brew-sencha";
    const view = render(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
    // What Next.js does after the Server Action revalidates: renders the page again, and sends the
    // comments it has now as new props, in the same response.
    const serverSends = async () => {
      view.rerender(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
      await flush();
    };
    const listed = () => screen.queryAllByRole("listitem").map((item) => item.textContent);
    const box = () => screen.getByLabelText("Your comment");
    const heading = () => screen.getByRole("heading", { level: 2 }).textContent;
    const post = async (text) => {
      await user.type(box(), text);
      await user.click(screen.getByRole("button", { name: "Post" }));
    };
    const kenji = "Kenji: Tried it overnight. So smooth.";
    const mei = "Mei: Works with genmaicha too!";
    await post("  Lovely with lemon  ");
    expect(listed()).toEqual([kenji, mei, "Ana: Lovely with lemon (sending…)"]);
    expect(heading()).toBe("Comments (3)");
    expect(box()).toHaveValue("");
    expect(screen.getByRole("button", { name: "Post" })).toBeDisabled();
    expect(sent).toEqual([{ postSlug: SLUG, text: "Lovely with lemon" }]);
    expect(comments[SLUG]).toHaveLength(2);
    
  3. settles on the server's fresh comments, showing the new one once
    const clock = useFakeTimers();
    const SLUG = "cold-brew-sencha";
    const view = render(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
    // What Next.js does after the Server Action revalidates: renders the page again, and sends the
    // comments it has now as new props, in the same response.
    const serverSends = async () => {
      view.rerender(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
      await flush();
    };
    const listed = () => screen.queryAllByRole("listitem").map((item) => item.textContent);
    const box = () => screen.getByLabelText("Your comment");
    const heading = () => screen.getByRole("heading", { level: 2 }).textContent;
    const post = async (text) => {
      await user.type(box(), text);
      await user.click(screen.getByRole("button", { name: "Post" }));
    };
    const kenji = "Kenji: Tried it overnight. So smooth.";
    const mei = "Mei: Works with genmaicha too!";
    await post("Lovely with lemon");
    await clock.advance(500);
    await serverSends();
    expect(listed()).toEqual([kenji, mei, "Ana: Lovely with lemon"]);
    expect(heading()).toBe("Comments (3)");
    expect(screen.getByRole("button", { name: "Post" })).toBeEnabled();
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    
  4. takes the comment back and returns the text when the server refuses it
    const clock = useFakeTimers();
    const SLUG = "cold-brew-sencha";
    const view = render(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
    // What Next.js does after the Server Action revalidates: renders the page again, and sends the
    // comments it has now as new props, in the same response.
    const serverSends = async () => {
      view.rerender(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
      await flush();
    };
    const listed = () => screen.queryAllByRole("listitem").map((item) => item.textContent);
    const box = () => screen.getByLabelText("Your comment");
    const heading = () => screen.getByRole("heading", { level: 2 }).textContent;
    const post = async (text) => {
      await user.type(box(), text);
      await user.click(screen.getByRole("button", { name: "Post" }));
    };
    const kenji = "Kenji: Tried it overnight. So smooth.";
    const mei = "Mei: Works with genmaicha too!";
    commentsService.closed = true;
    await post("Lovely with lemon");
    await clock.advance(500);
    await serverSends();
    expect(listed()).toEqual([kenji, mei]);
    expect(heading()).toBe("Comments (2)");
    expect(screen.getByRole("alert")).toHaveTextContent("Comments are closed for a few minutes. Try again soon.");
    expect(box()).toHaveValue("Lovely with lemon");
    expect(screen.getByRole("button", { name: "Post" })).toBeEnabled();
    
  5. takes it back when the connection drops, and posting again clears the message
    const clock = useFakeTimers();
    const SLUG = "cold-brew-sencha";
    const view = render(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
    // What Next.js does after the Server Action revalidates: renders the page again, and sends the
    // comments it has now as new props, in the same response.
    const serverSends = async () => {
      view.rerender(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
      await flush();
    };
    const listed = () => screen.queryAllByRole("listitem").map((item) => item.textContent);
    const box = () => screen.getByLabelText("Your comment");
    const heading = () => screen.getByRole("heading", { level: 2 }).textContent;
    const post = async (text) => {
      await user.type(box(), text);
      await user.click(screen.getByRole("button", { name: "Post" }));
    };
    const kenji = "Kenji: Tried it overnight. So smooth.";
    const mei = "Mei: Works with genmaicha too!";
    commentsService.offline = true;
    await post("Steeped mine for 12 hours");
    await clock.advance(500);
    expect(listed()).toEqual([kenji, mei]);
    expect(screen.getByRole("alert")).toHaveTextContent("Couldn't post your comment. Check your connection and try again.");
    expect(box()).toHaveValue("Steeped mine for 12 hours");
    commentsService.offline = false;
    await user.click(screen.getByRole("button", { name: "Post" }));
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    expect(listed()).toEqual([kenji, mei, "Ana: Steeped mine for 12 hours (sending…)"]);
    await clock.advance(500);
    await serverSends();
    expect(listed()).toEqual([kenji, mei, "Ana: Steeped mine for 12 hours"]);
    
  6. sends nothing for a blank comment
    const clock = useFakeTimers();
    const SLUG = "cold-brew-sencha";
    const view = render(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
    // What Next.js does after the Server Action revalidates: renders the page again, and sends the
    // comments it has now as new props, in the same response.
    const serverSends = async () => {
      view.rerender(<Comments postSlug={SLUG} comments={await getComments(SLUG)} viewerName="Ana" />);
      await flush();
    };
    const listed = () => screen.queryAllByRole("listitem").map((item) => item.textContent);
    const box = () => screen.getByLabelText("Your comment");
    const heading = () => screen.getByRole("heading", { level: 2 }).textContent;
    const post = async (text) => {
      await user.type(box(), text);
      await user.click(screen.getByRole("button", { name: "Post" }));
    };
    const kenji = "Kenji: Tried it overnight. So smooth.";
    const mei = "Mei: Works with genmaicha too!";
    await user.type(box(), "   ");
    await user.click(screen.getByRole("button", { name: "Post" }));
    await clock.advance(500);
    expect(sent).toEqual([]);
    expect(listed()).toEqual([kenji, mei]);
    expect(heading()).toBe("Comments (2)");
    

Learn more

app/journal/[slug]/comments.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).