Skip to the code

A currency picker that saves through a Server Action

Leaf and Kettle shows prices in the customer's currency, which it keeps in a currency cookie. Write the tea list, app/teas/page.tsx, an async Server Component.

Read the currency cookie with cookies() from next/headers. It can be USD, EUR, or GBP, the codes in CURRENCIES from @/lib/money; without the cookie, or with any other value, use USD.

Render an <h1> with Our teas, then CurrencyPicker from ./currency-picker, then a list with an item for each tea from getTeas() in @/lib/teas, like Green tea: €3.68, with the price from formatPrice(tea.price, currency).

CurrencyPicker is a Client Component: a select that calls the function in its saveCurrency prop with the code the customer picks. Give it currency, currencies (CURRENCIES), and saveCurrency. A Server Component can't pass an ordinary function to a Client Component, since a function can't be sent to the browser, but it can pass a Server Action: write saveCurrency(code) in the page as an async function whose body starts with "use server".

saveCurrency sets the currency cookie for the whole site (path: "/"), for a year (maxAge is in seconds: 60 * 60 * 24 * 365), with sameSite: "lax". A Server Action can be called by anyone with any argument, so it sets nothing when the code isn't one of CURRENCIES. After a Server Action sets a cookie, Next.js renders the page again and sends it back in the same response, so the prices change with no more code.

Cookie: currency=EUR
→ <h1>Our teas</h1>
  <CurrencyPicker currency="EUR" currencies={["USD", "EUR", "GBP"]} saveCurrency={saveCurrency} />
  Green tea: €3.68   Mint tea: €2.76   Oolong tea: €4.60
 
Picking GBP → Set-Cookie: currency=GBP; Path=/; Max-Age=31536000; SameSite=lax

The app's other files

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

export const CURRENCIES = ["USD", "EUR", "GBP"];
 
const RATES: Record<string, number> = { USD: 1, EUR: 0.92, GBP: 0.79 };
const SYMBOLS: Record<string, string> = { USD: "$", EUR: "€", GBP: "£" };
 
/** A price in dollars, in `currency` (one of CURRENCIES): formatPrice(4, "EUR") is "€3.68". */
export function formatPrice(dollars: number, currency: string) {
  return SYMBOLS[currency] + (dollars * RATES[currency]).toFixed(2);
}

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

export type Tea = { slug: string; name: string; price: number };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea", price: 4 },
  { slug: "mint", name: "Mint tea", price: 3 },
  { slug: "oolong", name: "Oolong tea", price: 5 },
];
 
/** Every tea, in the shop's order, priced in US dollars. */
export async function getTeas(): Promise<Tea[]> {
  return teas;
}

app/teas/currency-picker.tsx, read-only. Import it as @/app/teas/currency-picker.

"use client";
 
import { useTransition } from "react";
 
/** A select of the shop's currencies. Picking one calls `saveCurrency` with its code. */
export default function CurrencyPicker({
  currency,
  currencies,
  saveCurrency,
}: {
  currency: string;
  currencies: string[];
  saveCurrency: (currency: string) => Promise<void>;
}) {
  const [isPending, startTransition] = useTransition();
 
  return (
    <label>
      Currency{" "}
      <select
        defaultValue={currency}
        disabled={isPending}
        onChange={(event) => {
          const next = event.target.value;
          startTransition(() => saveCurrency(next));
        }}
      >
        {currencies.map((code) => (
          <option key={code} value={code}>
            {code}
          </option>
        ))}
      </select>
    </label>
  );
}

What the tests check

  1. shows prices in US dollars when there's no cookie
    const items = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const pickerProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === CurrencyPicker) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    await renderServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "Our teas" })).toBeInTheDocument();
    expect(items()).toEqual(["Green tea: $4.00", "Mint tea: $3.00", "Oolong tea: $5.00"]);
    expect(screen.getByLabelText("Currency")).toHaveValue("USD");
    
  2. shows prices in the currency the cookie names
    const items = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const pickerProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === CurrencyPicker) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    await withRequest({ cookies: { currency: "EUR" } }, () => renderServer(<Page />));
    expect(items()).toEqual(["Green tea: €3.68", "Mint tea: €2.76", "Oolong tea: €4.60"]);
    expect(screen.getByLabelText("Currency")).toHaveValue("EUR");
    cleanup();
    await withRequest({ cookies: { currency: "GBP" } }, () => renderServer(<Page />));
    expect(items()[2]).toBe("Oolong tea: £3.95");
    
  3. uses US dollars for a cookie it doesn't know
    const items = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const pickerProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === CurrencyPicker) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    for (const currency of ["JPY", "eur", ""]) {
      await withRequest({ cookies: { currency } }, () => renderServer(<Page />));
      expect(items()[0]).toBe("Green tea: $4.00");
      cleanup();
    }
    
  4. picking a currency sets the cookie through the Server Action
    const items = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const pickerProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === CurrencyPicker) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    await withRequest({ cookies: { currency: "EUR" } }, async (request) => {
      await renderServer(<Page />);
      await user.selectOptions(screen.getByLabelText("Currency"), "GBP");
      await flush();
      expect(request.setCookies.map(({ name, value, path, maxAge, sameSite }) => ({ name, value, path, maxAge, sameSite }))).toEqual([
        { name: "currency", value: "GBP", path: "/", maxAge: 31536000, sameSite: "lax" },
      ]);
      // Next.js renders the page again in the same response, with the new cookie.
      cleanup();
      await renderServer(<Page />);
      expect(items()[0]).toBe("Green tea: £3.16");
    });
    
  5. the Server Action sets nothing for a code the shop doesn't offer
    const items = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const pickerProps = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === CurrencyPicker) found.push(node.props);
          else if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    await withRequest({ cookies: { currency: "EUR" } }, async (request) => {
      const [picker] = await pickerProps(<Page />);
      expect(picker.currency).toBe("EUR");
      expect(picker.currencies).toEqual(["USD", "EUR", "GBP"]);
      await picker.saveCurrency("JPY");
      await picker.saveCurrency("gbp");
      await picker.saveCurrency(undefined);
      expect(request.setCookies).toEqual([]);
      await picker.saveCurrency("USD");
      expect(request.setCookies.map((cookie) => cookie.value)).toEqual(["USD"]);
    });
    

Learn more

app/teas/page.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).