Xstate: How to determine current (non-parallel) state logically?

Created on 23 Feb 2018  路  2Comments  路  Source: davidkpiano/xstate

I must be missing something, but I'm not seeing an out-of-the-box way of determining the current state logically (e.g., in a switch statement). Imagine this statechart:

screen shot 2018-02-23 at 3 16 07 pm

  • machine.initialState will be "logIn"
  • If I trigger transition LOG_IN the state returned is {"logIn": "loggingIn"}

This is quite reasonable for a human to interpret, but programmatically it makes me wonder if I'm supposed to perform typeof state == 'string' tests, and then for (let name in state) if it's an object to extract the current state name.

Am I missing a utility or property that can let me do the following?

const topLevelStateName = ?;
switch (topLevelStateName) {
  case 'logIn':
    handleTheLogInStuff();
    break;
  case 'home':
    handleTheHomeStuff();
    break;
}

To clarify, here's sort of what I'd expect (let's pretend this code doesn't know when/if the statechart changes):

let state = machine.initialState;
if (Math.random() < 0.5) {
  // To demonstrate that we don't want to know if FSM has progressed or not.
  state = machine.transition(state, 'LOG_IN'); // who knows where this might go?
}
if (state[0] == 'logIn') {
  // We're still handling login.
  // Based on the chart above, state would be one of the following:
  // ["logIn", "input"]
  // ["logIn", "loggingIn"]
}

Of course, if you take this to be a proposal, let's come up with a non-breaking change and not what I showed above. :)

documentation

Most helpful comment

This isn't documented (yet), but there is matchesState:

// syntax: matchesState(parentStateValue, childStateValue)
import { Machine, matchesState } from 'xstate';

// ...

const state = machine.transition(...);

if (matchesState('logIn', state.value)) {
  // if you're here, then state.value at least has the same 'logIn' parent state!
}

All 2 comments

This isn't documented (yet), but there is matchesState:

// syntax: matchesState(parentStateValue, childStateValue)
import { Machine, matchesState } from 'xstate';

// ...

const state = machine.transition(...);

if (matchesState('logIn', state.value)) {
  // if you're here, then state.value at least has the same 'logIn' parent state!
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hnordt picture hnordt  路  3Comments

ifokeev picture ifokeev  路  3Comments

greggman picture greggman  路  3Comments

laurentpierson picture laurentpierson  路  3Comments

suku-h picture suku-h  路  3Comments