1

Assuming we have the following simplified hierarchical xstate machine...

const HFSM = Machine({
  initial: 'init',
  states: {
    init: {
      initial: 'leaf'
    }
  }
});

...what is the best way to get its initial state?

Note that HFSM.initial returns me 'init' rather than {init: 'leaf'}

sookie
  • 2,437
  • 3
  • 29
  • 48

2 Answers2

1

At console.log(HFSM) we can see properties of this statemachine, and also its methods, in proto property. The initial state is on HFSM.initialState, and if the value is what we are looking for, that is HFSM.initialState.value

Log into the console the following and observe the properties of returned object:

HFSM.getInitialState() = the initial state of the machine, which is not started yet, and no transition attempts were made
- changed: undefined
- value: {}
- event: {type: "xstate.init"}

HFSM.initialState
- changed: undefined
- value: {init: "leaf"}
- event: {type: "xstate.init"}

HFSM.transition(HFSM.initialState, 'FAKE_EVENT')= tries to transition from initial state (not state name - https://xstate.js.org/docs/guides/transitions.html#machine-transition-method ), with a fake event so does nothing and remains in the state the machine tried to transition from
- changed: false
- value: {init: "leaf"}
- event: {type: "FAKE_EVENT"}

HFSM.transition(HFSM.initialState, 'REAL_EVENT')
- changed: true
- value: {init: "leaf2"}
- event: {type: "REAL_EVENT"}


Starting with xstate.js version 4.0 looks like we can use an interpreter, which can "keep track of the current state", among other useful things. https://xstate.js.org/docs/guides/interpretation.html#interpreter.

So once this service is initialized: const serv = interpret(HFSM) we can get initial state with: serv.start() or serv.init().

serv.start() === serve.init() // true

Tdk
  • 71
  • 4
0

The way I approached this was to invoke a fake transition:

const currentState = HFSM.transition(HFSM.initial, "fake").value;
sookie
  • 2,437
  • 3
  • 29
  • 48