โ† Over the wire ยท all materialsExercise 4 ยท 13 min ยท cases 1โ€“3 in class
Act 4 ยท POST

Leave a review

Taco Bike's page lists its reviews (GET /api/stalls/taco-bike/reviews, already done) and has a form. The form sends the review to the server with POST, renders what the server stored, and handles the server rejecting it. The Network tab shows exactly what your code sent.

The pattern. fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }). Success is 201 Created with the new resource in the body. Validation failures are 422 with { fields: { name: message } }: the API's contract is in api.html.

1

Send it

The form logs the review to the console and nothing else. Nobody will ever read it.

On submit, POST the review to `${STALL}/reviews` as JSON. The API wants rating as a number; every form value is a string. On 201, render the review from the response body (it has the server's id and createdAt) at the top of the list and reset the form. reviewItem(review) is done.

2

When the server says no

The server rejects a review that's too short, the page shows nothing, and the user retypes everything.

On 422, read fields from the body and put each message into the .field-error for that field (data-for), with aria-invalid="true" on its input; clear old errors on every submit. Any other failure, including no response at all, gets a sentence in .form-status. Never clear the form when it failed.

3

One click, one review

On a slow connection someone clicked Post three times. Taco Bike now has three identical reviews.

Disable the submit button while the request is in flight and put "Postingโ€ฆ" in .form-status. Re-enable it when the request is over, whether it succeeded, failed with a status, or failed without a response: that's what finally is for.