Skip to the code

Tea review Server Action

Each tea's page at Leaf and Kettle, /teas/<slug>, has a review form that uses useActionState. Write its Server Action, addReview(previous, formData), in app/actions.ts. The file starts with "use server", so every function it exports runs on the server.

The form sends three fields. Check each one, and return { errors } with a message for every field that's wrong, without saving anything:

tea, the tea's slug: it must be a tea the shop sells, which getTea(slug) from @/lib/teas finds. Otherwise the error is Choose a tea from the shop.

rating: a whole number from 1 to 5. Otherwise Pick a rating from 1 to 5.

text: the review, with spaces at the ends removed, from 10 to 500 characters long. Otherwise Write 10 to 500 characters.

When everything is right, save { tea, rating, text } with saveReview from @/lib/reviews (the rating as a number, the text trimmed), revalidate the tea's page with revalidatePath, so the new review shows, and redirect to /teas/<slug>#reviews.

addReview({ errors: {} }, formData)
// tea "mint", rating "6", text "Nice"
→ { errors: { rating: "Pick a rating from 1 to 5.", text: "Write 10 to 500 characters." } }

The app's other files

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

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);
}

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

export type Review = { tea: string; rating: number; text: string };
 
/** Every review saved so far. A real shop keeps them in its database. */
export const reviews: Review[] = [];
 
export async function saveReview(review: Review) {
  reviews.push(review);
  return review;
}

What the tests check

  1. saves a good review, revalidates the tea's page, and redirects to its reviews
    const where = await redirectOf(() => addReview({ errors: {} }, formData({ tea: "mint", rating: "5", text: "Cool, sweet, and fresh." })));
    expect(where).toEqual({ url: "/teas/mint#reviews", status: 307, type: "push" });
    expect(reviews).toEqual([{ tea: "mint", rating: 5, text: "Cool, sweet, and fresh." }]);
    expect(cache.revalidatedPaths).toEqual(["/teas/mint"]);
    
  2. saves the text without the spaces at its ends
    await redirectOf(() => addReview({ errors: {} }, formData({ tea: "oolong", rating: "4", text: "   Rich and smooth.  " })));
    expect(reviews).toEqual([{ tea: "oolong", rating: 4, text: "Rich and smooth." }]);
    
  3. returns an error for every wrong field, and saves nothing
    const state = await addReview({ errors: {} }, formData({ tea: "mint", rating: "6", text: "  Nice     " }));
    expect(state).toEqual({ errors: { rating: "Pick a rating from 1 to 5.", text: "Write 10 to 500 characters." } });
    expect(reviews).toEqual([]);
    expect(cache.revalidatedPaths).toEqual([]);
    
  4. only takes teas the shop sells
    const state = await addReview({ errors: {} }, formData({ tea: "coffee", rating: "5", text: "Strong and dark, my favorite." }));
    expect(state).toEqual({ errors: { tea: "Choose a tea from the shop." } });
    expect(reviews).toEqual([]);
    
  5. takes only whole ratings from 1 to 5, and text up to 500 characters
    for (const rating of ["0", "4.5", "", "five"]) {
      const state = await addReview({ errors: {} }, formData({ tea: "green", rating, text: "Light and fresh." }));
      expect(state.errors.rating).toBe("Pick a rating from 1 to 5.");
    }
    const long = await addReview({ errors: {} }, formData({ tea: "green", rating: "3", text: "a".repeat(501) }));
    expect(long).toEqual({ errors: { text: "Write 10 to 500 characters." } });
    expect(reviews).toEqual([]);
    
  6. shows its errors in a form with useActionState
    function ReviewForm() {
      const [state, action] = React.useActionState(addReview, { errors: {} });
      return (
        <form action={action}>
          <input type="hidden" name="tea" value="mint" />
          <label>Rating <input name="rating" /></label>
          <label>Review <textarea name="text" /></label>
          <button>Send</button>
          {state.errors.rating && <p>{state.errors.rating}</p>}
        </form>
      );
    }
    render(<ReviewForm />);
    await user.type(screen.getByLabelText("Rating"), "9");
    await user.type(screen.getByLabelText("Review"), "Cool and sweet, every time.");
    await user.click(screen.getByRole("button", { name: "Send" }));
    expect(await screen.findByText("Pick a rating from 1 to 5.")).toBeInTheDocument();
    expect(reviews).toEqual([]);
    

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).