Part 12 / Topic 3 of 7
useActionState — pending state and validation errors, no client fetch
// harness/app/swiggy-menu/reviews/ReviewForm.tsx (relevant excerpt)
const [state, formAction, pending] = useActionState(submitReview, initialReviewState);
submitReview's own signature matches exactly what useActionState requires — (prevState, formData) => newState, the installed forms.md guide's own documented shape:
// harness/app/swiggy-menu/reviews/actions.ts
export async function submitReview(_prevState: ReviewFormState, formData: FormData): Promise<ReviewFormState> {
const { name, ratingRaw, comment, rating, errors } = validate(formData);
if (Object.keys(errors).length > 0) {
return { errors, values: { name, rating: ratingRaw, comment } }; // no redirect - re-render with errors
}
addReviewRecord({ name, rating, comment });
updateTag("swiggy-reviews"); // section 6
redirect("/swiggy-menu/reviews?posted=1");
}
Submitting the exact same style of multipart POST section 2 used, but with invalid data (a blank name, a rating outside 1–5, a too-short comment), returns the errors directly in the response body — no separate error-fetching round trip, because useActionState's whole point is that the action's return value is the next render's state:
$ curl -s -X POST http://localhost:PORT/swiggy-menu/reviews -F 'name=' -F 'rating=9' -F 'comment=too short' ...
HTTP/1.1 200 OK
...
"errors":{"name":"Name should be 2-40 characters.","rating":"Pick a whole number rating between 1 and 5.","comment":"Review should be 10-280 characters."},"values":{"name":"","rating":"9","comment":"too short"}
Notice the response is 200, not a redirect — submitReview only calls redirect() on the success path; the validation-failure path returns the error state directly, and useActionState re-renders the form with it. The values echoed back in the state are what let ReviewForm.tsx's defaultValue={state.values.name} re-show exactly what the reviewer typed — without them, React resets an uncontrolled field after every action call, success or failure.
Done here? The practice set for Part 12 — including the solutions — is on the part page.