Personal Catalogue: React, Express & MongoDB — Chapter 8, Exercise 1 ===================================================================== TASK Replace the alert()-based error handling with inline error state, and add the titleInputRef focus behavior. Submit an invalid Book (missing author) and confirm the error appears inline with the form still usable, then add several valid books in a row without touching the mouse between submissions. SOLUTION AddItemForm.jsx (relevant additions): import { useState, useRef } from 'react'; const [error, setError] = useState(null); const titleInputRef = useRef(null); async function handleSubmit(e) { e.preventDefault(); setError(null); const payload = { /* ...unchanged from Chapter 4... */ }; const res = await fetch('http://localhost:4000/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); if (!res.ok) { const { error: message } = await res.json(); setError(message); return; } const created = await res.json(); onCreated(created); setShared({ title: '', releaseYear: '', notes: '' }); setTypeFields({}); titleInputRef.current?.focus(); } // in the JSX: {error &&
{error}
} Testing an invalid submission -- select Book, leave Author empty, submit: Output: an inline message appears near the form, reading the real Mongoose validation message (something like "Book validation failed: author: Path `author` is required."), and the rest of the page -- the item type dropdown, the title field, the list below -- all remain fully interactive the entire time. No dialog needed dismissing. Testing several valid additions in a row -- fill Author, submit, then immediately type the next book's title with no mouse click in between: Book 1: title "Dune", author "Frank Herbert" -> submit (cursor returns to the title field automatically) Book 2: title "Foundation", author "Isaac Asimov" -> submit (cursor returns again) Book 3: title "Neuromancer", author "William Gibson" -> submit Output: all three books appear in the list in order, and at no point was the mouse needed to click back into the title field -- confirming the focus-return behavior works across repeated successful submissions, not just the first one. WHY THIS WORKS AS AN ANSWER ---------------------------- It replaces the blocking alert with real inline state and verifies the form stays fully usable during a real validation failure, then verifies the focus-return behavior with a genuine multi-item sequence typed without touching the mouse -- the actual scenario Chapter 1's own deadline framing and this chapter's own opening paragraph describe, not just a single isolated success case.