npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xstate-async-guards

v1.1.0

Published

XState helper for using asynchronous guards

Downloads

746

Readme

xstate-async-guards

This is a helper for using asynchronous guards in XState state machines with ease.

npm version code style: prettier PRs Welcome

Rationale

Out of the box, XState supports only synchronous, pure condition functions (a.k.a. guards) in guarded transitions. This makes sense since synchronous transitions undertaken right after an event is received by a state machine are easy to conceptualize.

What if a guard needs external data from some asynchronous API (fetch, IndexedDB, etc.)? What if the guard execution is CPU intensive and you wish to offload it to a Web Worker? XState wants you to perform all async jobs in invoked services (or in spawned actors) which boils down to transitioning to some helper states first. That generates some boilerplate and may obscur your intentions. The problem is exacerbated when there are multiple async guard cases which need to be evaluated sequentially in a waterfall fashion.

The xstate-async-guards library provides a withAsyncGuards helper to abstract asynchronously guarded transitions like so:

// within a state machine declaration
states: {

  Idle: withAsyncGuards({
    on: {
      EVENT: {
        cond: async (_, event) => event.value === 'start', // async function!
        target: '#root.Started'
      }
    }
  }),

  Started: {}
}

Installation

$ npm install xstate-async-guards --save

Example

Simply wrap the state node with asynchronous guard functions in a withAsyncGuards call:

import { withAsyncGuards } from 'xstate-async-guards'

const machine = createMachine({
  id: 'root',
  context: {}, // must not be undefined
  initial: 'Idle',
  states: {
    // this state uses async guards
    Idle: withAsyncGuards({
      on: {
        EVENT: [
          {
            cond: isValueStart, // async function reference
            target: '#root.Started', // must use absolute targets
          },
          {
            cond: 'isValueFaulty', // string reference to an async function in configured guards
            target: '#root.Broken',
            actions: send('BROKEN'), // actions are supported
          },
          {
            target: '#root.Off', // default transition is optional
          },
        ],

        // rejected guard promises can be handled explicitly
        'error.async-guard.isValueStart': {
          actions: (_, event) => console.log('Async guard error!', event),
        },
      },

      id: 'idle', // state ID is mandatory

      // all standard state props are supported. E.g.:
      entry: () => console.log('entered Idle'),
      exit: () => console.log('exited Idle'),
      invoke: {
        /*...*/
      },
      // etc.
    }),

    Started: {},
    Broken: {},
    Off: {},
  },
})

Options

Function withAsyncGuards accepts an object as the second argument which may contain the following options:

  • inGuardEvaluation - an object with leading and trailing boolean props.
    • leading (boolean) - When true (default), in guards will be evaluated first, before async guards are evaluated. An async guard will be evaluated only if the in guard is satisfied.
    • trailing (boolean) - When true, in guards will be evaluated after async guards have been successfully resolved. If an in guard is not satisfied at this moment, the transition will not be taken (even though the async guard is satisfied). Defaults to false.

Caution

A thorough consideration should be given to consequences of using asynchronous guards for conditional transitions. Importantly, by the time an async guard resolves, the world may be in a state different from where it was at the time the event triggering the transition was received. Special care should be taken if your state machine uses parallel states or globally defined transitions.

TODO

  • Support combining sync and async guards within the same state node
  • Relax the requirement for absolute targets
  • Document error handling