Bitpath

Boss lesson · Unit 03

Fetch data

One request end to end: loading, error and success, the race between two responses, and refs.

13 exercisesabout 3 min

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)

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.

TypeScript
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.

TypeScript
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.

One email when Bitpath is ready to try. Nothing else. Privacy