Start learning free

LESSON 134 OF 161 · FRONTEND: FRONTEND WITH AI

Two Orders

Practice

An AI assistant wrote the checkout form. Its placeOrder sends the order and waits for the answer, and its button is always active:

async function placeOrder(event) {
  event.preventDefault();
  const response = await fetch("/api/orders", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: email }),
  });
  const data = await response.json();
  setMessage("Order " + data.id + " placed, total $" + data.total);
  onPlaced();
}
…
<button>Place order</button>

A request takes time to come back. While the first order is on its way, nothing on the screen has changed, so the visitor clicks again, or double-clicks out of habit. Each click sends one more POST /api/orders, and the shop places two orders.

The fix is a state that says a request is in flight, and a button that is disabled while it is true. A disabled button can't be clicked. For example, a newsletter form could use <button disabled={saving}>Subscribe</button>, with setSaving(true) before its request and setSaving(false) after the answer.

The check types an email, clicks "Place order", and prints the screen while the request is waiting. Your form must answer:

> click "Place order"
  request: POST /api/orders {"email": "ana@example.com"} ...
  screen while waiting:
    …
      button: Place order (disabled)
  answer: POST /api/orders {"email": "ana@example.com"} -> 201
  request: GET /api/cart -> 200
  screen changes:
    …
    -     button: Place order (disabled)
    +     button: Place order
    +     text: Order 1001 placed, total $24

Your task: in src/Checkout.jsx, the starting code has the email field and placeOrder, but no button. Add a state sending and a Place order button that is disabled while it is true. Set it to true before the request and back to false once the answer is read.


Assignment
Follow the Coding Tutorial to add the Place order button and turn it off while an order is on its way.


Hint
Turn sending on before the fetch, so the button is already off when a second click comes. Turn it off after data is read, or the button stays disabled for good.


STEP 1 OF 4
    Ctrl + Enter to check