読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
src/reservationApi.ts の、予約を送る関数です。
export async function createReservation(input: ReservationInput, key: string): Promise<Reservation> {
const body = await send("/reservations", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": key },
body: JSON.stringify(input),
});
return parse(ReservationSchema, body);
}
フォームの部品は、再送用のキーを1つ持ちます。
// 1回の予約の操作ごとに1つ。送り直すときも同じキーを使う
const [key, setKey] = useState(() => crypto.randomUUID());
crypto.randomUUID() は、ブラウザに用意された、重ならない文字列を作る関数です。予約が成功したら、次の予約のために新しいキーに替えます。失敗したときは替えません。通信の失敗のあとに「予約する」をもう一度押すと、同じキーで送り直され、予約が2件になることはありません。
送信中は、ボタンを押せなくし、文言を変えます。
<button type="submit" disabled={sending || items.length === 0}>
{sending ? "予約しています…" : "予約する"}
</button>
6 / 20