bus.register('cartAdd', addToCart, { undo: removeFromCart });
bus.use(optimisticUndo(bus, ['cartAdd'], {
predict: (cmd) => ({ id: cmd.target.id, qty: cmd.payload.qty }),
onRollback: (cmd, err) => toast.error(`Failed to add item: ${err.message}`),
}));
// dispatch returns immediately with predicted result
const result = await bus.dispatch('cartAdd', { id: 5 }, { qty: 2 });
// result.ok === true, result.value === { id: 5, qty: 2 }
Optimistic dispatch plugin that auto-rollbacks using the bus's registered undo handlers.
Unlike
optimistic(), this plugin does not require separateapply/rollback closures — it uses the undo handler already registered viaregister(action, handler, { undo }).How it works on an async bus:
{ ok: true, value: predict(cmd) }to the caller.On a sync bus: behaves like the regular
optimistic()— runs handler synchronously, rolls back via undo handler if it fails.Requires undo handlers to be registered for the targeted actions. Actions without undo handlers are passed through unchanged.