FSM as single source
One machine definition encodes every legal navigation. No scattered booleans or step indexes in component state.
This guide walks through the examples/checkout/ example: a six-step checkout wizard built on @input-actions/redux, driven entirely by one global state machine. By the end you’ll see how the library’s FSM + bindings + async action features compose into a real-world wizard that’s almost free of imperative UI plumbing.
cart ──→ address ──→ shipping ──→ payment ──→ review ──→ submitting ↑ ↑ ↑ ↑ ↑ │ └──────────┴───────────┴───────────┴────────────┘ │ ←─── (back) │ ↓ payment ←─── failed ←── submitting │ ↓ confirmed ─→ cart (after 5s)FSM as single source
One machine definition encodes every legal navigation. No scattered booleans or step indexes in component state.
Invariants gate transitions
Each forward step’s prerequisites live on the target state, not in components. Defence-in-depth even if dispatches come from elsewhere.
onEnter does async work
Fetching shipping rates, calculating tax, charging the card — all expressed as data on the relevant state.
Action graph closes loops
The charge action’s onSuccess / onError hold machine/transition tuples. No effect listens to the async op.
Machine-rooted bindings
One wizard.nav entry exposes different handlers per mode. The footer renders whichever exist.
DevTools time-travel
Every transition is one Redux action with the literal tuple as payload. Step backwards and forwards through the whole flow.
export type CheckoutMode = | 'cart' | 'address' | 'shipping' | 'payment' | 'review' | 'submitting' | 'confirmed' | 'failed';
export interface AppState { catalog: Record<string, CatalogItem>; cart: { lines: CartLine[] }; address: AddressFields; shipping: { rates: ShippingRate[]; selectedRateId: string }; payment: PaymentFields; taxCents: number; order?: Order; paymentError?: string; checkout: { mode: CheckoutMode; error?: string }; _async: Record<string, any>;}Each domain slice is independent. checkout.mode is what the FSM mutates. _async holds lifecycle metadata for in-flight handlers. The catalog is seeded; the cart starts non-empty so the demo opens on a populated cart.
export const checkoutMachine: StateMachineDefinition = { name: 'checkout', initialState: 'cart', states: { cart: { allowedTransitions: ['address'], }, address: { allowedTransitions: ['cart', 'shipping'], invariants: (state) => isCartNonEmpty(state) ? null : 'Cart is empty', }, shipping: { allowedTransitions: ['address', 'payment'], onEnter: [['action/async', 'fetch-rates', 'fetchShippingRates', { strategy: 'prevent' }]], invariants: (state) => isAddressValid(state) ? null : 'Address incomplete', }, payment: { allowedTransitions: ['shipping', 'review', 'submitting'], invariants: (state) => state.shipping.selectedRateId ? null : 'Pick a shipping option', }, review: { allowedTransitions: ['payment', 'submitting'], onEnter: [['action/async', 'calculate-tax', 'calculateTax', { strategy: 'allow' }]], invariants: (state) => isPaymentValid(state) ? null : 'Card details incomplete', }, submitting: { allowedTransitions: ['confirmed', 'failed'], onEnter: [ ['action/async', 'charge', 'chargeCard', { strategy: 'prevent', onSuccess: [['machine/transition', 'checkout', 'confirmed']], onError: [['machine/transition', 'checkout', 'failed']], }], ], }, confirmed: { allowedTransitions: ['cart'], onEnter: [['machine/delay', 'checkout', 'cart', 5000, [['action/reset']]]], }, failed: { allowedTransitions: ['payment', 'submitting'], }, },};A lot is happening here. Let’s unpack it.
The validator runs an invariant on the target of a transition. That means an invariant on state X encodes what the previous step had to satisfy before you can enter X.
Translation table:
| Invariant on | Enforces | Gates the transition |
|---|---|---|
address | cart non-empty | cart → address |
shipping | address valid | address → shipping |
payment | rate selected | shipping → payment |
review | card valid | payment → review |
submitting, confirmed, failed | — | no precondition (proven by prior gates) |
The cart state has no invariant — it’s the reset / initial state, always enterable.
onEnter hooks do async workWhen the FSM transitions into a state, its onEnter actions fire as part of the same dispatch. That gives us a natural place to initiate work the new state depends on:
shipping: { onEnter: [['action/async', 'fetch-rates', 'fetchShippingRates', { strategy: 'prevent' }]], // ...},No useEffect(() => { if (mode === 'shipping') fetch() }, [mode]) somewhere downstream. The fetch is wired into the state definition itself.
The most interesting piece. When the user clicks “Place order,” the FSM transitions into submitting. Its onEnter fires the charge:
submitting: { allowedTransitions: ['confirmed', 'failed'], onEnter: [ ['action/async', 'charge', 'chargeCard', { strategy: 'prevent', onSuccess: [['machine/transition', 'checkout', 'confirmed']], onError: [['machine/transition', 'checkout', 'failed']], }], ],},The async action’s onSuccess / onError fields hold machine/transition tuples. They go in the options object of plain action/async, with the strategy alongside; the shorthand forms such as action/async-prevent pass an object straight to the handler as an argument. When chargeCard resolves, the library dispatches onSuccess; when it rejects, onError. The machine transitions accordingly. No useEffect listens to _async.charge.status — the action graph closes the cycle as data.
machine/delay schedules an auto-resetconfirmed: { onEnter: [['machine/delay', 'checkout', 'cart', 5000, [['action/reset']]]],},Five seconds after landing on the confirmation page, the machine transitions back to cart and runs action/reset. The provider tracks the timer and clears it on unmount — no setTimeout cleanup in component code.
Three handlers, each demonstrating a different concurrency posture:
// src/handlers.ts (excerpt)export function createAsyncHandlers(store) { return { /** Strategy: prevent. No duplicate fetches if the user backs in and out. */ fetchShippingRates: async ({ signal }) => { await sleep(700); store.dispatch(['action/save', ['shipping', 'rates'], SHIPPING_RATES]); if (!store.getState().shipping.selectedRateId) { store.dispatch(['action/save', ['shipping', 'selectedRateId'], SHIPPING_RATES[0].id]); } return SHIPPING_RATES; },
/** Strategy: allow. Tax fetches are independent; no need to coordinate. */ calculateTax: async ({ signal }) => { await sleep(400); const tax = Math.round(computeSubtotal(store.getState()) * 0.07); store.dispatch(['action/save', ['taxCents'], tax]); return tax; },
/** Strategy: prevent. No double-submit. Throws ~1/3 of the time so the * failure-recovery path is easy to see. */ chargeCard: async ({ signal }) => { await sleep(1200); if (Math.random() < 0.33) { store.dispatch(['action/save', ['paymentError'], 'Card declined — please try again.']); throw new Error('Card declined'); } const order = { id: `ord-${++seq}`, totalCents: computeTotal(store.getState()), placedAt: Date.now() }; store.dispatch(['action/save', ['order'], order]); return order; }, };}Handlers close over the store so they can dispatch follow-up actions internally (saving the rates, the tax, the order). That’s the normalisation pattern from ADR 0008: _async is lifecycle metadata; the data the user cares about (the order) goes into a domain slice.
The throw in chargeCard becomes _async.charge.status === 'error', which in turn triggers the onError actions — which transition the machine to failed. The whole error path is encoded in data.
bindings.ts is the heart of the example’s “components stay thin” story. The whole wizard’s navigation is one machine-rooted entry:
// src/bindings.ts (the centrepiece)export const appBindings = defineBindings({ 'wizard.nav': { machine: 'checkout', modes: { cart: { onNext: [['machine/transition', 'checkout', 'address']] }, address: { onBack: [['machine/transition', 'checkout', 'cart']], onNext: [['machine/transition', 'checkout', 'shipping']], }, shipping: { onBack: [['machine/transition', 'checkout', 'address']], onNext: [['machine/transition', 'checkout', 'payment']], }, payment: { onBack: [['machine/transition', 'checkout', 'shipping']], onNext: [['machine/transition', 'checkout', 'review']], }, review: { onBack: [['machine/transition', 'checkout', 'payment']], onNext: [['machine/transition', 'checkout', 'submitting']], }, submitting: { // No controls — the in-flight charge closes the cycle. }, confirmed: { onReset: [['action/reset']], }, failed: { onBack: [['machine/transition', 'checkout', 'payment']], onRetry: [ ['action/save', ['_async', 'charge'], undefined], ['machine/transition', 'checkout', 'submitting'], ], }, }, }, // ... flat bindings for form fields, factory bindings for cart lines ...});What useBoundActions('wizard.nav') returns depends on the current mode:
cart, it returns { onNext }address, { onBack, onNext }confirmed, { onReset }failed, { onBack, onRetry }submitting, {} (nothing the user should do — the in-flight charge is in charge)The shared footer component just renders whichever buttons exist. No per-mode conditionals.
export default function WizardNav() { const handlers = useBoundActions('wizard.nav'); const gate = useStore((s) => prepareWizardGate(s), shallowEqualGate);
return ( <footer className="wizard-nav"> <div> {handlers.onBack && ( <button className="ghost" onClick={() => handlers.onBack?.()}>← Back</button> )} </div> <div> {!gate.canAdvance && gate.blockerMessage && ( <span className="hint hint-small">{gate.blockerMessage}</span> )} {handlers.onNext && ( <button onClick={() => handlers.onNext?.()} disabled={!gate.canAdvance}> Next → </button> )} {handlers.onReset && ( <button onClick={() => handlers.onReset?.()}>Start over</button> )} {handlers.onRetry && ( <button onClick={() => handlers.onRetry?.()}>Try again</button> )} </div> </footer> );}That’s the entire wizard footer for every step. Same component used by CartStep, AddressStep, ShippingStep, etc. The buttons that appear and what they do follow from the current machine mode.
gate is a pure derivation from state:
// src/prepare.ts (excerpt)export function prepareWizardGate(state) { switch (state.checkout.mode) { case 'cart': return state.cart.lines.length > 0 ? { canAdvance: true } : { canAdvance: false, blockerMessage: 'Add an item to continue.' }; case 'address': return isAddressValid(state) ? { canAdvance: true } : { canAdvance: false, blockerMessage: 'Fill all required fields.' }; case 'shipping': return state.shipping.selectedRateId ? { canAdvance: true } : { canAdvance: false, blockerMessage: 'Pick a shipping option.' }; case 'payment': return isPaymentValid(state) ? { canAdvance: true } : { canAdvance: false, blockerMessage: 'Card details incomplete.' }; case 'review': return { canAdvance: true }; default: return { canAdvance: false }; }}Each case mirrors the FSM invariant on the next state. Gate and invariant agree from different sides of the dispatch — the gate disables the button when prereqs aren’t met, the invariant blocks the dispatch as a final defence-in-depth.
With FSM + bindings + handlers absorbing the wiring, each step component just renders its slice and the shared footer:
// src/components/AddressStep.tsx (excerpt)export default function AddressStep() { const address = useStore((s) => s.address); const nameH = useBoundActions('address.name'); const line1H = useBoundActions('address.line1'); // ...
return ( <div className="step"> <h2>Shipping address</h2> <div className="form-grid"> <Field label="Full name" value={address.name} onChange={nameH.onChange} /> <Field label="Street" value={address.line1} onChange={line1H.onChange} /> {/* ... */} </div> <WizardNav /> </div> );}No onSubmit. No “is the form valid” computation. No “now move to the next step” logic. Just fields wired to bound handlers and the shared footer.
The SubmittingStep is the most extreme: it’s a spinner. That’s it. The charge async, the success/failure routing, the recovery loop — everything happens by way of action data flowing through the executor.
// src/components/SubmittingStep.tsx (entirety)export default function SubmittingStep() { return ( <div className="step submitting"> <div className="spinner" aria-hidden /> <h2>Charging your card…</h2> <p className="hint">This usually takes a second.</p> </div> );}// src/App.tsx (excerpt)import type { JSX } from 'react';
const STEP_COMPONENTS: Record<CheckoutMode, () => JSX.Element> = { cart: CartStep, address: AddressStep, shipping: ShippingStep, payment: PaymentStep, review: ReviewStep, submitting: SubmittingStep, confirmed: ConfirmedStep, failed: FailedStep,};
function CurrentStep() { const { currentMode } = useStateMachine('checkout'); const Step = STEP_COMPONENTS[currentMode] ?? CartStep; return <Step />;}The whole router. useStateMachine('checkout') reads currentMode; the map dispatches to the matching component. Exhaustiveness is enforced by Record<CheckoutMode, ...> — adding a new FSM mode without registering a component is a type error.
Single source of truth. The FSM definition is the authoritative model of how the wizard can move. Nothing else needs to know. Components, bindings, and gates all derive from it.
No useEffect reactor chains.
When submitting enters, the charge fires. When the charge succeeds or fails, the FSM transitions. All of it is action data — no components watching async statuses to decide what to do next.
Invariants are defence-in-depth.
The gate disables the Next button. The invariant also rejects the dispatch if it somehow reaches the machine (debug, devtools, programmatic machine/transition from elsewhere). Two layers, same predicate.
DevTools see everything.
Redux DevTools shows every transition as inputActions/executeAction with the literal action tuple. Click any past entry to time-travel; the FSM state slice replays exactly.
New steps are local additions.
Adding a “gift wrapping” step between payment and review is: a new mode in the FSM, an invariant on the next state, a new entry in wizard.nav, a new component, a new line in the step router. The existing components don’t change.
git clone https://github.com/aeftink/input-actionscd input-actionspnpm installpnpm --filter input-actions-checkout-example devOpens at http://localhost:3009/. Install Redux DevTools (browser extension) and watch the timeline as you click through. The chargeCard handler fails ~1 in 3 attempts, so the failed → payment | retry recovery path will show up within a few attempts.
Full source: examples/checkout/. The example’s own README has the file-by-file layout.
machine/* action.