Searching TVMaze
Fetch matching shows when Search is pressed, and show loading, error, or cards.
The handler can be async
Here is the watchlist as you left it. Type a name, press Search, and a
line reads Looking for: plus that name. Nothing talks to the network
yet.
TVMaze already knows those titles. Promises and
async/await taught fetch and await. A submit
handler can be async too.
This is the same fetch as the refresher, called from the click.
Mark handleSearch async. Call event.preventDefault() first, then
await fetch(...). Wrap the query with encodeURIComponent. Check
response.ok.
Type severance and press Search. The line waits, then reads how many
shows came back. The three cards stay.
Idle, loading, error, success
A request is not a value. It might still be going, or it might fail.
Keep status in state, starting at "idle". The first paint is idle:
no request has run. On submit, set "loading", then "success" or
"error".
Disable Search while status === "loading", so a slow reply cannot
easily pile up.
If the box is blank after trim(), set a short message and return. Do
not call fetch.
Press Search. The button waits until the reply lands. Clear the box and press Search again. The line asks for a name, and no request runs.
Map the payload
TVMaze does not send the shape ShowCard expects. Each hit is
{ score, show }. The title is show.name, not title. Some shows
have no poster, so show.image?.medium uses ?. from Working with
Objects.
Put a mapper in /show.js. Call it with item.show. Draw a
Results row. Do not add those cards to the watchlist yet.
If onToggle is missing, ShowCard hides the checkbox. Results are
display-only. When show.image is a string, render it inside the still.
Keep the gradient class as a fallback.
Do not put summary HTML into the page.
Search severance. Matching cards appear under Results. The three saved
cards stay below, with Watched checkboxes.
No matches
A reply can be empty. That is still "success", not "error". When
results.length === 0, show No shows for that name.
Try zzzznotashow in the sandbox above.
Common mistakes
- Fetching during render.
fetchin the component body runs every time React draws. Put it in the submit handler. - Skipping
response.ok.fetchonly rejects when the network fails. A 404 is still a reply. Checkresponse.ok, as in Promises and async/await. - Reading
results[0]while idle.resultsstarts as[].results[0].show.namethrows before anyone searches.
Exercise
Search is wired to TVMaze, but matching cards never appear. The seed list is fine on first paint.
Type severance and press Search. You should see a Results row of
cards, and the three saved shows still below.
On first paint the page should still show:
My watchlist
Search
The Bear
Severance
Andor
Hint: each item in the payload is { score, show }. Pass the inner
show to fromTvmaze.