Start learning free

LESSON 30 OF 58 · FULL-STACK: CART AND CHECKOUT

Show It on the Page

Practice

The server answers a wrong checkout form with 400 {"error": "Check the form", "fields": {…}}, one message per wrong field. But the checkout page shows only the alert "Check the form", and the visitor has to guess which field is wrong. The given api() in client/src/api.js already puts the answer's fields on the error it throws, as err.fields.

Keep those messages in a state object, errors, and show each one under its own input. Mark the input with aria-invalid, so a screen reader says it is wrong. What the visitor typed stays in the fields, because the inputs keep their own state. On a review form, one field would look like this:

<input
  id="review-text"
  value={text}
  onChange={(event) => setText(event.target.value)}
  aria-invalid={errors.text !== undefined}
  required
/>
{errors.text && <p>{errors.text}</p>}

The browser can also run quick checks before sending: required refuses an empty field, and pattern="[0-9]{5}" refuses anything but 5 digits. They save a trip to the server, but they are not the judge: " " is not empty to the browser, and a request sent without the page skips them all. The server still decides.

Ana has a Mug in her cart and clicks Place order four times. Then the check posts a bad order straight to the API:

all fields empty                        →  not sent: Name, Address and Postal code are empty
Ana Pop, "   ", 4000                    →  not sent: Postal code is not valid
Ana Pop, "   ", 40001                   →  400  Address (invalid), "Address is required", alert: Check the form
Ana Pop, Strada Lunga 5, 40001          →  200  Ready to pay: $12
POST /api/checkout {"name": "", "address": "", "postal_code": "abc"}
                                        →  400  {"error": "Check the form", "fields": {"address": "Address is required", "name": "Name is required", "postal_code": "Postal code must be 5 digits"}}

Your task: in client/src/pages/CheckoutPage.jsx, keep the server's field messages in errors, mark each wrong input with aria-invalid and show its message under it, then add the browser's quick checks.


Assignment
Follow the Coding Tutorial to show the server's message under each wrong field of the checkout form, and to add required and pattern to its inputs.


Hint
The server's key for the postal code is postal_code, not postalCode. An answer without fields must leave errors as an object: err.fields || {}.


STEP 1 OF 12
    Ctrl + Enter to check