Paul Razvan Berg
Paul Razvan Berg

Reputation: 21390

Transient transition that sets a value only on condition passing

Take the following code:

const isWarning = () => { ... }
const setWarning = () => { ... }

const machine = Machine({
  initial: "foo",
  context: {
    warning: null
  },
  states: {
    foo: {
      on: {
        "": [
          target: "bar",
          action: "setWarning",
          cond: "isWarning",
        ]
      }
    },
    bar: {
      on: {
        FOO: "foo,
      }
    }
  }
}, {
  actions: {
    setWarning
  }
  guards: {
    isWarning
  }
});

Is this the best way to go to "bar" and set a warning based on some quantitative data in "foo"?

Upvotes: 0

Views: 205

Answers (1)

Tdk
Tdk

Reputation: 71

Given the posted code example, I am not sure what you mean by "quantitative data in foo". Data relevant for machine's behavior can be stored in machine's context or state's meta property. For getting into bar state and set a warning you might need something like:


    const sm = Machine({
      initial: 'baz',
      context: { wasWarned: false },
      on: {
        'WARNING': {
            target: 'bar',
            action: 'setWarning'     
        }
      },
      states: {
        baz: {},
        bar: {}
      }  
    }, {
      actions: {
        setWarning: assign({ warning: true })
      }
    })

This means: When machine gets 'WARNING' event, go into bar state AND immediately, before anything else update the context.

Actions are not immediately triggered. Instead, the State object returned from machine.transition(...) will declaratively provide an array of .actions that an interpreter can then execute.

The transition will be enabled after the guards are passed.

Other code example that might prove useful depending on what you want to achieve:


const sm = Machine({
      initial: 'pending',
      context: { wasWarned: null },
      states: {
        pending: {
          on: {
            '': [
             {target: 'bar', cond:'wasWarned'},
             {target: 'baz', cond: 'otherCond'} 
            ]
          }
        },
        bar: {},
        baz: {}
      },
      guards: {
        wasWarned: (ctx) => ctx.wasWarned
      }
    })

Upvotes: 1

Related Questions