React · Chapter 23 of 26
Actions and forms
By the end of this chapter you can send a form with an action instead of a submit handler, keep a form's result, its errors and its busy state with useActionState, let a button know its form is busy with useFormStatus, and show the result of a click before the server has answered with useOptimistic. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real apps
- 4 tasks
- React
- In the all labs plan
The first 2 chapters of React are free. This one comes with the all labs plan.
Why you need this
The checkout page is where Parda earns its money, and where Datta's calls come from. Every form on it has the same four moments: someone types, presses the button, waits while the server thinks, and then sees either a result or a message. Ira's designs draw all four for every form: the button says what it is doing while it waits, it cannot be pressed twice, a message never sits beside an old one, and what was typed is still there after a mistake.
You can build all of that with what you know: a submit handler that calls preventDefault, a useState for the pending flag, another for the error, another for the result, and a try and catch that must set each one back on every path. Every form repeats that code, and every copy is a place to forget one line: a pending flag that is never set back leaves a button that says "Checking..." for ever. React 19 has a shorter way that leaves less to forget: actions.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
BookForm.jsx: the booking form, with an action
Make BookForm, with the props showtime (an object with an id, T0002) and seats (an array, ['D11', 'D12']), return a <form> whose action is the form action that useActionState gives you. The form holds a heading h2 that says Your details, an input labelled Name with name="name", an input labelled Phone with name="phone", and a button that says Book 2 seats (2 is seats.length).
When the form is sent, the action reads the two fields from its FormData. With no name, it shows Please enter your name.; with a phone that is not exactly 10 digits, it shows Please enter a 10-digit phone number.; neither calls the server. Otherwise it calls bookSeats({ showtime: showtime.id, seats, name, phone }) from api.js, once; while it waits, the button says Booking... and is disabled; if bookSeats fails, its error's message shows. Each message goes in an element with role="alert". When the booking comes back ({ id: 'PB81820' }), show, instead of the form, a paragraph with role="status" that says Booked! Your booking number is PB81820.
React empties a form's fields when its action finishes. After any message, the Name and Phone fields must still hold what was typed: the Check sends the form with no name, then with the phone 98220, then with 9822012345 (bookSeats fails with Seat D11 was just taken), then again (the booking comes back), and reads the fields and messages each time. Give the form className="book-form" for app.css.
- Task 2
SubmitButton.jsx: a button that knows its form is busy
Make SubmitButton, with the props children and pendingText, return a submit button that shows children; while the form it is inside is running its action, it shows pendingText instead and is disabled. So <SubmitButton pendingText="Saving...">Save</SubmitButton> says Save, then Saving... while its form's action runs, then Save again.
Read the form's state with useFormStatus from react-dom, called in SubmitButton itself. The Check puts SubmitButton in a form of its own whose action waits until the Check says so. App.jsx uses it in the reminder form; BookForm and PromoForm may use it too.
- Task 3
Interested.jsx: a count that answers at once
Make Interested, with the props showId and count, return a button that says Interested (412) for count 412. A click shows Interested (413) at once, before the server answers, and calls markInterested(showId) from api.js, once. When it answers with the new count (the Check answers 415, with other people's clicks in it), the button says Interested (415). If it fails, the button goes back to Interested (412) and the error's message (Could not save that. Try again.) shows in an element with role="alert".
Use useOptimistic for the number shown while the server thinks, and update it inside an action: a form's action, or a function given to startTransition. An optimistic update outside an action makes React print an error, and the Check fails on it.
- Task 4 · interview question
Interview: PromoForm.jsx, the promo form that gets stuck
PromoForm is written with onSubmit and useState. Type a code that is not Parda's, press Apply, and the button says Checking... for ever; type a good code after a bad one and the old error stays beside the discount. Rewrite it with useActionState and the form's action, with no onSubmit and no pending state of your own, so that it shows: an input labelled Promo code with name="code"; a button Apply that says Checking... and is disabled while applyPromo(code) from api.js runs (SubmitButton, Task 2, can do this); when applyPromo fails, its message in an element with role="alert"; when it answers { code: 'DIWALI20', off: 40 }, a paragraph with role="status" that says DIWALI20: ₹40 off; and only the last answer's message, never both.
The Check types DIWALI2 (applyPromo fails with DIWALI2 is not a Parda code.), then DIWALI20, and also reads PromoForm.jsx: it must call useActionState and have no onSubmit.
Rukhsana will ask: what does useActionState give you that onSubmit and useState did not?
What you will learn
- A form action: <form action={fn}> calls fn with the form's fields, with no preventDefault.
- FormData: how an action reads the fields, by their name.
- The reset: React empties a form's fields after its action, and how to keep them.
- useActionState: the action's result as state, the form action to give the form, and whether it is running.
- useFormStatus: a component inside a form reads whether that form is busy.
- useOptimistic: a value to show while an action runs, which falls back when it ends.
More in Real apps
Build "Actions and forms" yourself
Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of React are free. This one comes with the all labs plan.