Skip to the code

A to-try list that shows your change at once

Customers at Leaf and Kettle keep a to-try list: teas they want to taste, ticked off once they have. The /to-try page shows it from getToTry(userId), a "use cache" function tagged with the customer's own tag, to-try-<userId>, like to-try-ana. The home page shows Most wanted, the teas on the most lists, from getMostWanted(), tagged most-wanted. Both are in @/lib/to-try.

Write two Server Actions in app/actions.ts. Each gets the customer's id from getUserId() in @/lib/session, never from the form.

addTea(previous, formData) runs the Add form through useActionState. Its tea field, trimmed, must be 1 to 60 characters long, or it returns { error: "Name a tea, up to 60 characters." } and changes nothing. Otherwise it saves the tea with saveToTry(userId, tea) and returns { error: null }.

After saving, expire the customer's list with updateTag("to-try-<userId>"). They're looking at it and must see the new tea at once, and after updateTag, the page Next.js renders for the action's answer waits for fresh data. Most wanted is shared by everyone and can be a little behind, so mark it stale with revalidateTag("most-wanted", "max"), which keeps serving the old list while a fresh one is made in the background.

markTried(id), which each item's form binds to the item's id, ticks the item off with setTried(userId, id), then calls updateTag for the customer's list. Ticking off doesn't change Most wanted. When setTried returns false, because this customer has no item with that id, expire nothing.

addTea({ error: null }, formData)   // tea: "  Jasmine pearls "
→ saveToTry("ana", "Jasmine pearls")
→ updateTag("to-try-ana"), revalidateTag("most-wanted", "max")
→ { error: null }
 
markTried(3) → setTried("ana", 3) → updateTag("to-try-ana")

The app's other files

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

/** Who's signed in: a stand-in for reading the session cookie. */
export const session = { userId: "ana" };
 
export async function getUserId(): Promise<string> {
  return session.userId;
}

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

import { cacheTag } from "next/cache";
 
export type ToTryItem = { id: number; tea: string; tried: boolean };
 
/** Every customer's to-try list, by user id: a stand-in for the shop's database. */
export const lists: Record<string, ToTryItem[]> = { ana: [], ben: [] };
let nextId = 1;
 
export async function saveToTry(userId: string, tea: string): Promise<ToTryItem> {
  const item = { id: nextId++, tea, tried: false };
  (lists[userId] ??= []).push(item);
  return { ...item };
}
 
/** Ticks the item off. False when this customer has no item with that id. */
export async function setTried(userId: string, id: number): Promise<boolean> {
  const item = (lists[userId] ?? []).find((entry) => entry.id === id);
  if (!item) return false;
  item.tried = true;
  return true;
}
 
/** The /to-try page's list: cached, with the customer's own tag, like "to-try-ana". */
export async function getToTry(userId: string): Promise<ToTryItem[]> {
  "use cache";
  cacheTag(`to-try-${userId}`);
  return (lists[userId] ?? []).map((item) => ({ ...item }));
}
 
/** The home page's Most wanted: the teas on the most lists, cached with the tag "most-wanted". */
export async function getMostWanted(): Promise<string[]> {
  "use cache";
  cacheTag("most-wanted");
  const counts = new Map<string, number>();
  for (const items of Object.values(lists)) for (const item of items) counts.set(item.tea, (counts.get(item.tea) ?? 0) + 1);
  return [...counts].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([tea]) => tea);
}

What the tests check

  1. adds the tea and expires the customer's list with updateTag
    const state = await addTea({ error: null }, formData({ tea: "  Jasmine pearls " }));
    expect(state).toEqual({ error: null });
    expect(lists.ana).toEqual([{ id: 1, tea: "Jasmine pearls", tried: false }]);
    expect(cache.updatedTags).toEqual(["to-try-ana"]);
    
  2. marks Most wanted stale with the max profile, and nothing more
    await addTea({ error: null }, formData({ tea: "Sencha" }));
    expect(cache.calls.filter((call) => call.name === "revalidateTag")).toEqual([{ name: "revalidateTag", args: ["most-wanted", "max"] }]);
    expect(cache.updatedTags).not.toContain("most-wanted");
    expect(cache.revalidatedPaths).toEqual([]);
    
  3. uses the signed-in customer's own list and tag
    session.userId = "ben";
    await addTea({ error: null }, formData({ tea: "Hojicha" }));
    expect(lists.ben).toEqual([{ id: 1, tea: "Hojicha", tried: false }]);
    expect(lists.ana).toEqual([]);
    await markTried(1);
    expect(lists.ben[0].tried).toBe(true);
    expect(cache.updatedTags).toEqual(["to-try-ben", "to-try-ben"]);
    
  4. turns down an empty or long name and expires nothing
    for (const fields of [{ tea: "" }, { tea: "    " }, { tea: "x".repeat(61) }, {}]) {
      expect(await addTea({ error: null }, formData(fields))).toEqual({ error: "Name a tea, up to 60 characters." });
    }
    expect(lists.ana).toEqual([]);
    expect(cache.calls).toEqual([]);
    expect(await addTea({ error: null }, formData({ tea: "y".repeat(60) }))).toEqual({ error: null });
    expect(lists.ana).toHaveLength(1);
    
  5. markTried ticks the item off and updates only the customer's list
    await saveToTry("ana", "Mint tea");
    await saveToTry("ana", "Sencha");
    await markTried(2);
    expect(lists.ana.map((item) => item.tried)).toEqual([false, true]);
    expect(cache.updatedTags).toEqual(["to-try-ana"]);
    expect(cache.revalidatedTags).toEqual([]);
    
  6. markTried expires nothing for an item that isn't on the customer's list
    await saveToTry("ben", "Mint tea");
    await markTried(1);
    await markTried(99);
    expect(lists.ben[0].tried).toBe(false);
    expect(cache.calls).toEqual([]);
    
  7. works from forms: useActionState to add, a bound form to tick off
    function ToTry() {
      const [state, add] = React.useActionState(addTea, { error: null });
      return (
        <>
          <form action={add}>
            <label>Tea <input name="tea" /></label>
            <button>Add</button>
            {state.error && <p role="alert">{state.error}</p>}
          </form>
          <ul>
            {lists.ana.map((item) => (
              <li key={item.id}>
                <form action={markTried.bind(null, item.id)}>
                  <button>Tried {item.tea}</button>
                </form>
              </li>
            ))}
          </ul>
        </>
      );
    }
    render(<ToTry />);
    await user.click(screen.getByRole("button", { name: "Add" }));
    await flush();
    expect(screen.getByRole("alert")).toHaveTextContent("Name a tea, up to 60 characters.");
    await user.type(screen.getByLabelText("Tea"), "Jasmine pearls");
    await user.click(screen.getByRole("button", { name: "Add" }));
    await flush();
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Tried Jasmine pearls" }));
    await flush();
    expect(lists.ana).toEqual([{ id: 1, tea: "Jasmine pearls", tried: true }]);
    expect(cache.updatedTags).toEqual(["to-try-ana", "to-try-ana"]);
    

Learn more

app/actions.tsSaved 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).