1

I have the following code, the condition in start state is giving me trouble.

const machine = require('xstate');
let test = true;

// Stateless machine definition
// machine.transition(...) is a pure function used by the interpreter.
const helloMachine = machine.Machine({
    id: 'hello',
    initial: 'start',
    states: {
        start: {
            on: {
                STOP: {
                    target: 'stop',
                    actions: ['hi'],

                    // ! something is wrong with cond structure
                    cond: () => test === false // returns either true or false, which signifies whether the transition should be allowed to take place
                }
            }
        },
        stop: {
            entry: ['hello'], // The action(s) to be executed upon entering the state node.
            type: 'final'
        }
    }
}, {
    actions: {
        hello: (context, event) => {
            const hello = 'Hello World';
            console.log(hello)
        },

        hi: () => {
            test = false;
            console.log(`${test} -> ${typeof(test)}`);
        }
    }
})

// Machine instance with internal state
const helloService = machine.interpret(helloMachine)

helloService.start();
helloService.send('STOP');

As I see it, if test is false it should proceed to the next state. Initially test = true, in the hi action I switch is to false, and then check the condition, if cond: () => test === false the next state doesn't run, but if cond: () => test === true it runs.

Is there a mistake in the code, or mu understanding of cond is wrong?

Yury Stanev
  • 419
  • 1
  • 5
  • 16

1 Answers1

1

Your understanding of cond isn't quite correct. A transition is taken only if the guard (the cond expression) passes (i.e., evaluates to true).

Taking a transition means:

  • transitioning to the target state (if any)
  • executing actions (if any)

Actions are not executed on a transition unless it is taken, and because the guard is preventing the transition from being taken, the action that sets test = false will not be executed.

Also, please prevent external mutations (the test variable lives outside the machine). It makes the state machine less deterministic, which defeats the purpose of using a state machine.

David Khourshid
  • 4,918
  • 1
  • 11
  • 10