Why Finity?
A component that loads something usually ends up with a handful of flags: isLoading, data, error. Nothing stops isLoading being true while error is set from the last attempt, and every place that reads them has to guess which combinations are possible.
finity replaces the flags with states. A component is in exactly one state at a time, and each state carries only the data it has:
const Resource = finity
.defineTransitionalState<{
Loading: {};
Ready: { resource: Resource };
Errored: { error: Error };
}>()
.transitions({ Loading: ["Ready", "Errored"], Ready: [], Errored: [] });There's no error to read in Ready, and no way to be in Loading and Errored at once.
Transitions are declared
transitions lists, for each state, the states that may follow it. A state only changes by calling transition on the current state, and TypeScript accepts only the states its entry lists. Ready: [] makes Ready terminal: its transition takes nothing at all.
So the ways a component can move between states are written in one place, and code that tries any other way doesn't compile. See Defining states.
Every state is handled
Renders take one case per state, in a chain that ends in use():
return finity
.useRender(state.value)
.case(["Loading"], () => <Spinner />)
.case(["Ready"], ({ resource }) => <Resource resource={resource} />)
.case(["Errored"], ({ error }) => <Failure error={error} />)
.use();use can only be called once every state has a case. Add a state, and every render that doesn't handle it becomes a type error naming the missing state. See Rendering.
Late transitions are refused
A request that resolves after the component has moved on would normally still write its result. In finity, a transition belongs to the state it came from, and once that state has been left, calling it does nothing. finity reports it to onInvalidTransition instead, so a slow response can't overwrite a newer state. See Invalid transitions.
When not to use it
- The state is a single value with no rules, like a text input or a toggle. Your framework's own state is simpler.
- The state is shared across many components. finity manages a component's own state. For app-wide state, use a store, and model the states it holds with plain unions.
- You don't use TypeScript. Most of what finity checks, it checks at compile time.
