Write a Server Action that adds a tea to a cart kept in a cookie
Each tea's page has an Add to cart button in a form that uses useActionState. Write its Server Action, addToCart(previous, formData), in app/actions.ts. The cart is a cookie named cart: the slugs of the teas in it, joined by commas, like green,mint.
Read the form's tea field, the tea's slug. If getTea(slug) from @/lib/teas finds no such tea, return { message: "Choose a tea from the shop." } and change nothing. If the tea is already in the cart, return { message: "Mint tea is already in your cart." }, with the tea's name, and change nothing.
Otherwise add the slug to the end of the cart and set the cookie again: for a week (maxAge in seconds), readable only by the server (httpOnly), on every path. Revalidate /cart, so the cart page shows the new tea, and return { message: "Mint tea is in your cart." }.
app/actions.ts"use server";
import { cookies } from "next/headers";
import { revalidatePath } from "next/cache";
import { getTea } from "@/lib/teas";
export type CartState = { message: string };
export async function addToCart(previous: CartState, formData: FormData): Promise<CartState> {
const slug = String(formData.get("tea"));
return { message: "Added." };
}
lib/teas.ts (read-only)export type Tea = { slug: string; name: string };
const teas: Tea[] = [
{ slug: "green", name: "Green tea" },
{ slug: "mint", name: "Mint tea" },
{ slug: "oolong", name: "Oolong tea" },
];
/** The tea with this slug, or undefined when the shop doesn't sell it. */
export async function getTea(slug: string): Promise<Tea | undefined> {
return teas.find((tea) => tea.slug === slug);
}
- adds a tea to an empty cart, as a cookie only the server reads, for a week
- adds the tea after the teas already in the cart
- revalidates the cart page after a change
- leaves the cart alone when the tea is already in it
- refuses a tea the shop doesn't sell, and a form without one
- shows its message in a form with useActionState
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…