Boss lesson · Unit 03
Fetch data
One request end to end: loading, error and success, the race between two responses, and refs.
What you practise
- Loading, error and success states, the race between two requests and the cleanup that fixes it, refs for values that do not render
Try a question from this lesson
Pick one
A profile page asks a server for its data. What can the component render at 100 ms?
0 ms component appears, request starts
300 ms response arrives (or fails)Correct answer
A loading state: the data does not exist yet
Why
Rendering is a synchronous function call: it returns at once with whatever state exists right now. At 100 ms that state says "still waiting", so the screen must show that. The response later sets state, and a new render shows data or an error.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Three states
A request is in exactly one of three situations, and each needs different data. A union type with a tag says so precisely: "loading with an error" cannot be written, and TypeScript will not let you read users before you have checked the tag. One state variable holds the whole thing.
type State =
| { kind: 'loading' }
| { kind: 'error'; msg: string }
| { kind: 'ok'; users: string[] };Concept
The cleanup that fixes the race
In a component the same idea is an effect with a cleanup. When id changes, React runs the cleanup of the previous effect before starting the next, so the old response is ignored whenever it arrives. The same cleanup covers a component that is removed while its request is still on the way.
useEffect(() => {
let ignore = false;
getUser(id).then(u => {
if (!ignore) setUser(u);
});
return () => { ignore = true; };
}, [id]);10 more exercises in the app
- 5× multiple choice
- 1× order the lines
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× type the answer
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.