Skip to content

Shopping Cart

A checkout flow for a shopping cart, built to demonstrate machina’s defer() mechanism. An input sent at the wrong time, like a coupon click while validation runs, gets queued and replayed automatically when the FSM enters a state that can handle it. The caller fires the input once, and the FSM replays it at the right time.

  • defer({ until: "stateName" }): queue an input to replay when the FSM enters a specific named state
  • defer() (untargeted): queue an input to replay on the next transition to any state, used in the error state’s catch-all handler
  • _onEnter / _onExit lifecycle hooks: _onEnter starts an async timer and stores the ID on context, and _onExit clears it so stale callbacks can’t fire into the wrong state
  • State-driven UI: buttons enable and disable based on the current state. The confirm button appears in checkout alone, and the checkout button stays disabled until the cart has items
State What happens
browsing Idle. Accepts addItem, applyCoupon, checkout (if items > 0). recordPurchaseAnalytics defers to checkout.
validating Async inventory/price check (~2s). applyCoupon and checkout defer to browsing.
applyingDiscount Async discount calculation (~1.8s). addItem, applyCoupon, and checkout all defer to browsing.
reservingInventory Intent chokepoint (~1.5s). This state doesn’t defer: an unhandled input emits nohandler and drops.
checkout Review page. Deferred recordPurchaseAnalytics inputs replay here. confirm transitions to confirmed.
confirmed Terminal state. Only reset works.
error Not in the normal flow. Demonstrates untargeted defer() via a catch-all "*" handler. Reachable via fsm.transition("error") from the console.

Targeted defer with defer({ until: "stateName" })

Section titled “Targeted defer with defer({ until: "stateName" })”

The user clicks “Apply Coupon” while validation is already running. The FSM is in validating and can’t handle the input yet. The handler defers it to browsing and spares the caller a retry:

// validating state
applyCoupon({ defer }) {
    defer({ until: "browsing" });
},

When validationComplete fires and the FSM transitions to browsing, machina automatically replays the deferred applyCoupon input. Machina preserves FIFO order, so three clicks replay as three inputs in sequence.

The same pattern queues recordPurchaseAnalytics across several state transitions. The handlers defer it to checkout from browsing, validating, and applyingDiscount. It waits in the queue through as many cycles as the flow needs, then runs exactly once per queued entry.

// browsing, validating, applyingDiscount states
recordPurchaseAnalytics({ defer }) {
    defer({ until: "checkout" });
},

// checkout state: this is where it finally runs
recordPurchaseAnalytics({ emit }) {
    emit("analyticsRecorded");
},

The error state uses a catch-all "*" handler without a target state. The deferred inputs replay on the next transition to any state, and the destination state handles them:

error: {
    "*"({ defer }) {
        // Park everything. Whatever state we land in next will handle it.
        defer();
    },
    retry: "browsing",
    reset({ ctx }) {
        ctx.itemCount = 0;
        return "browsing";
    },
},

Untargeted defer fits the case where the recovery destination is unknown at defer time. Error classification and retry logic pick the next state, and the queued inputs replay there.

examples/shopping-cart/