Write a Server Action that checks a tasting-box order and returns each field's error to useActionState
Leaf and Kettle sells tasting boxes: three different teas, a number of boxes, and an optional gift note. The order form at /tasting-box is a Client Component that runs orderTastingBox(previous, formData) through useActionState, starting from initialBoxState in @/lib/tasting-box. Write the action in app/tasting-box/actions.ts.
The form sends teas once for each ticked checkbox (every tea's checkbox is named teas, with the tea's slug as its value), boxes as typed, and note. A field that's missing counts as empty. Check all three, and give a message for each one that's wrong:
teas must be exactly three different slugs of teas that getTea from @/lib/teas finds, or Pick 3 different teas.; boxes must be a whole number from 1 to 10 written only in digits, like 3, or Choose from 1 to 10 boxes.; note, with spaces at its ends removed, can be empty and is at most 140 characters, or Keep the note to 140 characters.
When anything is wrong, save nothing and return { errors, values }: errors with a message for each wrong field and no key for the others, and values with what the form sent, untouched (the slugs in the order they came, boxes and note as typed), so the form can show it all again.
When everything is right, save { teas, boxes, note } with saveBoxOrder from @/lib/orders (boxes as a number, the note trimmed), which returns the order's id, and redirect to /orders/<id>. Don't catch errors from saveBoxOrder: a database that's down isn't something the customer can fix, so the error should reach the error boundary.
// teas=mint, teas=green, teas=rooibos, boxes=2, note=" Happy birthday, Ana! "
// → saveBoxOrder({ teas: ["mint", "green", "rooibos"], boxes: 2, note: "Happy birthday, Ana!" })
// → redirect("/orders/1001")
// teas=green, teas=coffee, boxes=0, note=""
// → { errors: { teas: "Pick 3 different teas.", boxes: "Choose from 1 to 10 boxes." },
// values: { teas: ["green", "coffee"], boxes: "0", note: "" } }
app/tasting-box/actions.ts"use server";
import { redirect } from "next/navigation";
import { getTea } from "@/lib/teas";
import { saveBoxOrder } from "@/lib/orders";
import type { BoxState } from "@/lib/tasting-box";
export async function orderTastingBox(previous: BoxState, formData: FormData): Promise<BoxState> {
const teas = formData.getAll("teas").map(String);
return { errors: {}, values: { teas, boxes: "1", note: "" } };
}
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" },
{ slug: "rooibos", name: "Rooibos" },
];
/** 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);
}
lib/orders.ts (read-only)export type BoxOrder = { teas: string[]; boxes: number; note: string };
/** Every order saveBoxOrder saved, in order: the stand-in database's rows. */
export const savedOrders: BoxOrder[] = [];
let down = false;
/** Makes the stand-in database fail, as a real one does when it can't be reached. */
export function setDatabaseDown(value: boolean) {
down = value;
}
/** Saves the order and returns its id, like "1001". Throws when the database is down. */
export async function saveBoxOrder(order: BoxOrder): Promise<string> {
if (down) throw new Error("The order database is down.");
savedOrders.push(order);
return String(1000 + savedOrders.length);
}
lib/tasting-box.ts (read-only)export type BoxFields = { teas: string[]; boxes: string; note: string };
/** What the tasting-box form shows: a message for each field that's wrong, and what was sent. */
export type BoxState = {
errors: { teas?: string; boxes?: string; note?: string };
values: BoxFields;
};
export const initialBoxState: BoxState = { errors: {}, values: { teas: [], boxes: "1", note: "" } };
- returns a message for every wrong field at once, with what was sent, and saves nothing
- saves a right order, with the boxes as a number and the note trimmed, and redirects to it
- takes only exactly three different teas the shop sells
- takes only a whole number of boxes from 1 to 10, written in digits
- keeps the note optional, and up to 140 characters once trimmed
- lets a database failure reach the error boundary instead of returning it
- shows its errors in a form with useActionState, which keeps what was ticked and typed
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…