completefrontend

Write the codeMedium

A customer posts a review. Which cached data should the Server Action expire with updateTag, and which with revalidateTag?

Customers review teas with a form on each tea's page, /teas/<slug>, whose useActionState calls postReview(previous, formData) in app/teas/[slug]/actions.ts. The action already checks who's posting and what they sent, and saves the review. A review with a link in it is held for staff, and anyone else sees it only once they approve it. What's left is telling the cache, and right now it calls revalidatePath, which reaches neither of the other pages that show reviews.

@/lib/reviews shows what each page reads and its tag: the tea's page lists its published reviews under reviews:<slug>, the catalog at /teas shows every tea's average stars under ratings, and each customer's account page lists their own reviews, held ones included, under my-reviews:<customerId>. Replace the revalidatePath call. The customer must see their published review in the page the action sends back, and their account page must show the new review, published or held, the next time they open it. The catalog is the busiest page in the shop, and its stars can be a moment late. A held review changes nothing anyone else sees. Refused reviews revalidate nothing, as they already do.

Write this: app/teas/[slug]/actions.ts
"use server";
 
import { revalidatePath } from "next/cache";
import { getCustomer } from "@/lib/session";
import { needsModeration, saveReview } from "@/lib/reviews";
 
export type ReviewState = { error: string | null; message: string | null };
 
const TEAS = ["green", "mint", "oolong"];
const fail = (error: string): ReviewState => ({ error, message: null });
 
export async function postReview(previous: ReviewState, formData: FormData): Promise<ReviewState> {
  const customer = await getCustomer();
  if (!customer) return fail("Sign in to post a review.");
 
  const slug = String(formData.get("slug") ?? "");
  const stars = Number(formData.get("stars"));
  const text = String(formData.get("text") ?? "").trim();
  if (!TEAS.includes(slug)) return fail("There's no such tea.");
  if (!Number.isInteger(stars) || stars < 1 || stars > 5) return fail("Choose from 1 to 5 stars.");
  if (!text || text.length > 500) return fail("Write a review of up to 500 characters.");
 
  const held = needsModeration(text);
  await saveReview({ slug, customerId: customer.id, stars, text, status: held ? "held" : "published" });
 
  revalidatePath(`/teas/${slug}`);
 
  return {
    error: null,
    message: held ? "Thanks! Staff will check your review before it goes up." : "Thanks, your review is up.",
  };
}
lib/session.ts (read-only)
import { cookies } from "next/headers";
 
export type Customer = { id: string; name: string };
 
/** Signed-in customers by session token, the value of the `session` cookie: a stand-in for the session store. */
const sessions = new Map<string, Customer>([
  ["token-ana", { id: "c_ana", name: "Ana" }],
  ["token-ben", { id: "c_ben", name: "Ben" }],
]);
 
/** The customer who sent this request, or null. */
export async function getCustomer(): Promise<Customer | null> {
  const token = (await cookies()).get("session")?.value;
  return (token && sessions.get(token)) || null;
}
lib/reviews.ts (read-only)
import { cacheLife, cacheTag } from "next/cache";
 
export type Review = { slug: string; customerId: string; stars: number; text: string; status: "published" | "held" };
 
/** Every review: a stand-in for the shop's database. */
export const reviews: Review[] = [];
 
/** A review with a link in it waits for staff before anyone else sees it. */
export function needsModeration(text: string): boolean {
  return /https?:\/\/|www\./i.test(text);
}
 
export async function saveReview(review: Review) {
  reviews.push(review);
}
 
// The cached reads behind the shop's pages, and the tags each is cached under.
 
/** A tea's published reviews, on its page, /teas/<slug>, where the review form is. */
export async function getReviews(slug: string) {
  "use cache";
  cacheTag(`reviews:${slug}`);
  cacheLife("max");
  return reviews.filter((review) => review.slug === slug && review.status === "published");
}
 
/** Every tea's average stars, on the catalog, /teas, the busiest page in the shop. */
export async function getRatings() {
  "use cache";
  cacheTag("ratings");
  cacheLife("max");
  const ratings: Record<string, { stars: number; count: number }> = {};
  for (const review of reviews) {
    if (review.status !== "published") continue;
    const rating = (ratings[review.slug] ??= { stars: 0, count: 0 });
    rating.stars += review.stars;
    rating.count += 1;
  }
  return ratings;
}
 
/** A customer's own reviews, published or waiting, on /account/reviews. */
export async function getMyReviews(customerId: string) {
  "use cache";
  cacheTag(`my-reviews:${customerId}`);
  cacheLife("max");
  return reviews.filter((review) => review.customerId === customerId);
}
The tests your code must pass
  • a published review expires the tea's reviews with updateTag
  • the customer's own reviews expire with updateTag, published or held
  • the catalog's ratings are marked stale with a profile, not expired
  • a held review changes nothing anyone else sees
  • no revalidatePath, and the tags follow the tea and the customer
  • a refused review revalidates nothing

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…