Skip to content
Logo

Quick start

This page builds a component that loads a resource and shows it, or shows the error. The code is the same in React and Solid except where the tabs say otherwise.

1. Install

2. Initialize once

Call initialize in one module, and import finity's functions from there:

initialize takes options for reporting invalid transitions and comparing states. See Invalid transitions and Equal states. This module is also the place to rename anything you'd like to call something else.

3. Define the states

List each state and the data it carries, then which states may follow each one:

// src/Resource.ts
import * as finity from "./finity";
 
export const Resource = finity
  .defineTransitionalState<{
    Loading: {};
    Ready: { resource: string };
    Errored: { error: Error };
  }>("Resource")
  .transitions({ Loading: ["Ready", "Errored"], Ready: [], Errored: [] });

Every state also gets a kind property, its name. The "Resource" argument names the state machine in error messages, and is optional.

4. Use them in a component

useStrictlyTransitionalState holds the state, starting from the initial value its function returns. useRender renders the current state, with one case per state.

Loading has work to do, so it gets its own component, which starts the request in your framework's own effect. The component exists as long as the state does, so leaving Loading aborts the request:

In React, the effect depends on state, which keeps its identity until the state changes. In Solid, a case runs once when its state starts, like a component, so read the state's properties in JSX rather than destructuring them, and start the work in the component body. See Effects.

5. See what it checks

  • Remove a case. Delete the Errored case from useRender, and .use() stops compiling: Type 'UnhandledStates<"Errored">' has no call signatures.
  • Transition somewhere undeclared. Call transition({ kind: "Loading" }) from Ready, and it doesn't compile, since Ready: [] allows nothing.
  • Transition late. Even without the abort, a response that arrives after the state has changed can't overwrite it. Its transition does nothing, and onInvalidTransition is told why.

Next