React Foundations · TypeScript

Modelling state as a union

Discriminated union state

Modelling state as a union

A request is never loading and loaded and failed at once. It is in exactly one of those situations. Model it with several independent booleans, though, and nothing stops the impossible combinations: isLoading and data and error all true. A discriminated union makes the states mutually exclusive instead:

type RequestState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string }
  | { status: 'error'; error: string };

Every member carries a literal status — the discriminant. Narrow on it and TypeScript gives you exactly the fields of that member, and no others:

const [state, setState] = useState<RequestState>({ status: 'idle' });

state.status === 'success' && <p>{state.data}</p>;

Inside the success branch, state is { status: 'success'; data: string }, so state.data is safe. In the idle branch, state.data is a type error — which is the point: the compiler stops you reading data that is not there.

Because the union lists every member, one branch per status covers the whole state machine, and a new member surfaces every place that must handle it.

Your job is to model a request as a discriminated union in App.tsx and render each state.

Challenge

A request moves through several states, and the screen has to show each one. Export an App component from App.tsx that keeps a RequestState discriminated union in useState, starting at idle. Render a Load button whose click moves the state to loading and then to success with data: 'Loaded'. Render one paragraph per state: Idle, Loading…, the data, or the error.

The Test expects Idle first, then Loading… after it clicks your button, then Loaded. The starter never leaves Idle, so the Test fails.

App.tsx
export function App() {
  return (
    <div>
      <button>Load</button>
      <p>Idle</p>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.