Xstate: Multiple guarded targets

Created on 9 Oct 2019  路  2Comments  路  Source: davidkpiano/xstate

Hey, I was wondering if it is possible to add guards to multiple targets.

The documentation shows how multiple targets can be specified within a single event but I'm not sure if it's also already possible to add guards.

In a slightly modified version from the example, I would maybe only want to transition to the inactive mode once the queue inside the context is empty:

id: 'settings',
type: 'parallel',
context: {
  queue: []
},
states: {
  mode: {
    initial: 'active',
    states: {
      inactive: {},
      pending: {},
      active: {}
    }
  },
  status: {
    initial: 'enabled',
    states: {
      disabled: {},
      enabled: {}
    }
  }
},
on: {
  // Multiple targets
  DEACTIVATE: {
    target: ['.mode.inactive', '.status.disabled'] // <--- How do I add a guard to the first target?
  }
}
question

Most helpful comment

You have to split into 2 transitions, one guarded and one unguarded:

{
  on: {
    DEACTIVATE: [{
      cond: ctx => ctx.queue.length === 0,
      target: ['.mode.inactive', '.status.disabled']
    }, {
      target: ['.status.disabled']
    }]
  }
}

All 2 comments

You have to split into 2 transitions, one guarded and one unguarded:

{
  on: {
    DEACTIVATE: [{
      cond: ctx => ctx.queue.length === 0,
      target: ['.mode.inactive', '.status.disabled']
    }, {
      target: ['.status.disabled']
    }]
  }
}

Nice! Thank you for the quick response. I was about to do something hacky 馃槃

Was this page helpful?
0 / 5 - 0 ratings

Related issues

amelon picture amelon  路  3Comments

dakom picture dakom  路  3Comments

hnordt picture hnordt  路  3Comments

hnordt picture hnordt  路  3Comments

rodinhart picture rodinhart  路  3Comments