Lesson 7
Fetch & UI states
Build a practical mental model for fetch & ui states and use it in working JavaScript.
By the end, you will be able to…
- Explain fetch & ui states in your own words
- Use fetch & ui states in a small program
- Recognize and debug a common failure mode
Build the mental model
Every real fetch needs at least four UI states: idle, loading, success, and error — and empty as a fifth when success returns nothing. Skipping any of them leaves users staring at a blank or frozen screen.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Handling all states explicitly is what separates a demo from a production-quality feature that behaves well on slow networks or failures.
Real-world example
A search results page showing a spinner, then either results, a 'no results' empty state, or a retry button on failure covers exactly these states.
Common mistakes
- Only handling the success case and leaving users stuck on a spinner forever if the request fails
- Forgetting a distinct empty state when success returns an empty array
- Not offering a retry action on the error state
Try it yourself
Challenge
Write classifyResult(result) returning 'error' | 'empty' | 'success' from a { ok, data } shape.
Knowledge check
Besides loading and success, what other UI state do real fetches need?
Summary
Model loading, success, empty, and error as explicit UI states — never assume the request will simply succeed.