Skip to content

Event Reference

Every state change in StateMesh emits an event. Events use a discriminated union — TypeScript narrows the shape based on the type field.

Event Types

TypeWhen
state.changedAny state change
state.resetmesh.reset() called
action.startedAction handler begins
action.completedAction handler finishes
action.errorAction handler throws
transaction.startedTransaction begins
transaction.optimisticOptimistic update applied
transaction.completedTransaction commits
transaction.errorTransaction fails
transaction.rollbackTransaction rolls back
transaction.retryTransaction retries
resource.fetchResource fetch starts
resource.successResource fetch succeeds
resource.errorResource fetch fails
resource.invalidatedResource cache invalidated
mutation.startedMutation begins
mutation.completedMutation succeeds
mutation.errorMutation fails
form.submittedForm submitted
form.validatedForm validated
form.autosavedForm autosaved
url.changedURL state changed
persist.loadedPersistence loaded
persist.savedPersistence saved
sync.receivedCross-tab message received
sync.sentCross-tab message sent

Event Shape

ts
interface MeshEvent {
  type: string;          // Event type (discriminator)
  name?: string;         // Action/transaction/resource/mutation name
  timestamp: number;     // Date.now()
  metadata?: Record<string, unknown>;  // Event-specific data
}

Subscribe to Events

ts
// All events
mesh.subscribe((state) => state, (state) => { /* ... */ });

// Specific event type
mesh.on({ type: "action.completed" }, (event) => {
  console.log(event.name);
});

// Wildcard
mesh.on({ type: "resource.*" }, (event) => {
  console.log(event.type);
});

// RegExp
mesh.on({ type: /error$/ }, (event) => {
  console.error(event);
});

Important Notes

TIP

Events are fire-and-forget. Listeners are error-isolated — they never break state mutations.

Released under the MIT License.