読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第3節 入力を確かめて結果を返す

3.2 useActionState でまちがいを表示する

フォームを Client Components にして、Server Actions の結果を受け取ります。

// src/components/ReserveForm.tsx
"use client";

import { useActionState } from "react";
import { reserveProduct, type ReserveState } from "@/app/products/[id]/actions";

const initialState: ReserveState = {};

export const ReserveForm = ({ productId }: { productId: string }) => {
  const [state, formAction, isPending] = useActionState(reserveProduct, initialState);

  return (
    <form action={formAction}>
      <input type="hidden" name="productId" value={productId} />
      <label htmlFor="name">お名前</label>
      <input id="name" name="name" aria-describedby="name-error" />
      {state.errors?.name && <p id="name-error">{state.errors.name[0]}</p>}

      <label htmlFor="quantity">個数</label>
      <input id="quantity" name="quantity" type="number" defaultValue={1} aria-describedby="quantity-error" />
      {state.errors?.quantity && <p id="quantity-error">{state.errors.quantity[0]}</p>}

      <button type="submit" disabled={isPending}>
        {isPending ? "送っています…" : "予約する"}
      </button>
    </form>
  );
};
戻り値意味
stateServer Actions が最後に返した結果
formAction&lt;form action&gt; に渡す関数
isPending送っている途中なら true

送っている途中はボタンを押せなくし、二重に予約されないようにしています。aria-describedby は、入力欄とまちがいの文を結び付ける属性です。入力欄のアクセシビリティは、カリキュラム「品質を保つ:アクセシビリティ・性能・セキュリティ」で詳しく扱います。

解答の例

名前の欄の下に「お名前を入力してください」、個数の欄の下に「1回の予約は10個までです」が表示されます。予約は記録されず、ページも移動しません。

12 / 17