Skip to the code

Helpful votes that answer at once and roll back

Under each review on a tea's page, Leaf and Kettle shows a Helpful (12) button: a toggle that marks the review as helpful, or takes the mark back. Saving a vote with voteHelpful(reviewId, helpful), a Server Action in app/actions.ts, takes 400 ms, and the button should answer the click at once. Write it, app/teas/[slug]/helpful-button.tsx, a Client Component whose default export is HelpfulButton({ reviewId, count, voted }): the review's id, its helpful count, and whether this visitor has already marked it, all from the server.

The button's text is Helpful (12), with the count, and its aria-pressed says whether the visitor has marked the review. A click flips the mark and moves the count by one, up or down, straight away, then calls voteHelpful(reviewId, true) to mark it or voteHelpful(reviewId, false) to take the mark back. Use React's useOptimistic for what the button shows while the vote is saving.

When voteHelpful answers { ok: true, helpful }, show that count: it's the server's, and it may include other customers' votes.

When it answers { ok: false, error }, or the call itself throws because the connection dropped, put the button back to the last saved count and mark, and show Couldn't save your vote. Try again. in an element with role="alert". The next click clears the message.

While a vote is saving, the button ignores more clicks.

<HelpfulButton reviewId="r1" count={12} voted={false} />
click             → Helpful (13), aria-pressed="true", at once
400 ms later      → the server's count: Helpful (13), or more if others voted too
if saving fails   → Helpful (12), aria-pressed="false", Couldn't save your vote. Try again.

The app's other files

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

export type Review = { id: string; author: string; text: string; helpful: number; voted: boolean };
 
/** Each review's helpful count, as the database has it. */
export const helpfulCounts: Record<string, number> = { r1: 12, r2: 5 };
 
/** Every vote the server was asked to save, in order. */
export const votes: { reviewId: string; helpful: boolean }[] = [];
 
/** Set `down` and the votes service answers with an error. Set `offline` and the call fails without an answer. */
export const votesService = { down: false, offline: false };
 
const reviews = [
  { id: "r1", author: "Kenji", text: "Fresh, like spring.", voted: false },
  { id: "r2", author: "Ana", text: "My morning cup.", voted: true },
];
 
/** The tea's reviews, with their helpful counts and whether this visitor marked each one. */
export async function getReviews(): Promise<Review[]> {
  return reviews.map((review) => ({ ...review, helpful: helpfulCounts[review.id] }));
}

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

"use server";
 
import { helpfulCounts, votes, votesService } from "@/lib/reviews";
 
export type VoteResult = { ok: true; helpful: number } | { ok: false; error: string };
 
/** How long the votes service takes to answer. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
/**
 * Marks the review as helpful (`helpful` true) or takes the mark back (false), and answers the
 * review's new count. Takes 400 ms.
 */
export async function voteHelpful(reviewId: string, helpful: boolean): Promise<VoteResult> {
  votes.push({ reviewId, helpful });
  await wait(400);
  if (votesService.offline) throw new TypeError("Failed to fetch");
  if (votesService.down) return { ok: false, error: "The votes service is down." };
  helpfulCounts[reviewId] += helpful ? 1 : -1;
  return { ok: true, helpful: helpfulCounts[reviewId] };
}

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

import { getReviews } from "@/lib/reviews";
import HelpfulButton from "./helpful-button";
 
export default async function TeaPage() {
  const reviews = await getReviews();
 
  return (
    <main>
      <h1>Sencha</h1>
      <ul>
        {reviews.map((review) => (
          <li key={review.id}>
            <p>
              {review.author}: {review.text}
            </p>
            <HelpfulButton reviewId={review.id} count={review.helpful} voted={review.voted} />
          </li>
        ))}
      </ul>
    </main>
  );
}

What the tests check

  1. is a Client Component the server-rendered reviews can show
    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 helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    await renderOnServer(<Page />);
    expect(helpful(12)).toHaveAttribute("aria-pressed", "false");
    expect(helpful(5)).toHaveAttribute("aria-pressed", "true");
    await user.click(helpful(12));
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    
  2. shows the vote at once, before the server answers
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    render(<HelpfulButton reviewId="r1" count={12} voted={false} />);
    await user.click(helpful(12));
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    expect(votes).toEqual([{ reviewId: "r1", helpful: true }]);
    expect(helpfulCounts.r1).toBe(12);
    await clock.advance(400);
    expect(helpfulCounts.r1).toBe(13);
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    
  3. settles on the server's count, which can include other customers' votes
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    helpfulCounts.r1 = 20;
    render(<HelpfulButton reviewId="r1" count={12} voted={false} />);
    await user.click(helpful(12));
    expect(helpful(13)).toBeInTheDocument();
    await clock.advance(400);
    expect(helpful(21)).toHaveAttribute("aria-pressed", "true");
    
  4. takes a mark back, and ignores clicks while a vote is saving
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    render(<HelpfulButton reviewId="r2" count={5} voted={true} />);
    await user.click(helpful(5));
    expect(helpful(4)).toHaveAttribute("aria-pressed", "false");
    await user.click(helpful(4));
    expect(helpful(4)).toHaveAttribute("aria-pressed", "false");
    await clock.advance(800);
    expect(votes).toEqual([{ reviewId: "r2", helpful: false }]);
    expect(helpful(4)).toHaveAttribute("aria-pressed", "false");
    
  5. rolls back and says so when the server answers with an error
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    votesService.down = true;
    render(<HelpfulButton reviewId="r1" count={12} voted={false} />);
    await user.click(helpful(12));
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    await clock.advance(400);
    expect(helpful(12)).toHaveAttribute("aria-pressed", "false");
    expect(screen.getByRole("alert")).toHaveTextContent("Couldn't save your vote. Try again.");
    expect(helpfulCounts.r1).toBe(12);
    
  6. rolls back when the call throws, and the next click clears the message
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    votesService.offline = true;
    render(<HelpfulButton reviewId="r1" count={12} voted={false} />);
    await user.click(helpful(12));
    await clock.advance(400);
    expect(helpful(12)).toHaveAttribute("aria-pressed", "false");
    expect(screen.getByRole("alert")).toHaveTextContent("Couldn't save your vote. Try again.");
    votesService.offline = false;
    await user.click(helpful(12));
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    await clock.advance(400);
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    
  7. a failed vote goes back to the last saved count, not the first one
    const helpful = (count) => screen.getByRole("button", { name: `Helpful (${count})` });
    const clock = useFakeTimers();
    render(<HelpfulButton reviewId="r1" count={12} voted={false} />);
    await user.click(helpful(12));
    await clock.advance(400);
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    votesService.down = true;
    await user.click(helpful(13));
    expect(helpful(12)).toHaveAttribute("aria-pressed", "false");
    await clock.advance(400);
    expect(helpful(13)).toHaveAttribute("aria-pressed", "true");
    expect(screen.getByRole("alert")).toHaveTextContent("Couldn't save your vote. Try again.");
    

Learn more

app/teas/[slug]/helpful-button.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).