Learning on Web Dev Open is free for all.

Systems Thinking > Shape the data before you write the UIMake the impossible unrepresentable
Phase 03Shape the data before you write the UI153 of 434

Make the impossible unrepresentable

Four booleans give you sixteen states and you meant four. The extra twelve are where the bugs live.

Concept14 minAI pair

isLoading, isError, data, error. That is sixteen combinations and you meant four: idle, loading, loaded with data, failed with an error. The other twelve, loading and errored at once, loaded with no data, errored with no error, are states your code can enter and your rendering has never considered.

A discriminated union collapses them: { status: "idle" } | { status: "loading" } | { status: "success", data: T } | { status: "error", error: E }. Now data exists only where it is meaningful, the compiler refuses to let you read it in the loading branch, and a switch over status can be checked for exhaustiveness so adding a fifth state produces errors everywhere it needs to be handled.

The technique generalises beyond fetch states. A form field that is either untouched, editing with a draft value, or committed. A subscription that is either inactive, trialling with an end date, or paid with a renewal date. Every time you find yourself writing "this field is only set when that other field is true", you have found a union waiting to be named.

You should now be able to

  • Replace a set of correlated flags with a union
  • Explain why the compiler can then check your rendering
Ask the community

Loading…