xstate icon indicating copy to clipboard operation
xstate copied to clipboard

Bug: State entry action's actor value mismatch

Open carlos-sonatafy opened this issue 1 year ago • 10 comments
trafficstars

XState version

XState version 5

Description

While trying to read the actor's current value/active state using self.getSnapshot().value, the actual value is that of the actor before entering the new state.

As an example, consider the following statechart:

https://stately.ai/registry/editor/embed/0e3cf46a-a74e-4fc2-8161-dcbcec137965?machineId=522c8104-73e6-40d6-922c-30917b52733f

const myAction = assign(({ self }) => {
  console.log(self.getSnapshot().value);

  return {};
})

The action prints First State instead of Second State.

Expected result

Because the action is an entry action for a specific state - not a transition - I'd expect the actual value to be Second State

Actual result

The value is First State

Reproduction

https://stately.ai/registry/editor/0e3cf46a-a74e-4fc2-8161-dcbcec137965?machineId=522c8104-73e6-40d6-922c-30917b52733f

Additional context

No response

carlos-sonatafy avatar May 23 '24 14:05 carlos-sonatafy

This is working as expected. The snapshot isn't committed until all of the actions have been executed.

davidkpiano avatar May 24 '24 05:05 davidkpiano

@davidkpiano I mean, I understand that portion - and I know my knowledge about statecharts is lesser than yours - but it kind of doesn't make sense.

If we're talking about an action that executes while entering a state, shouldn't said action be able to consult the statechart's active state?

And if that holds true, shouldn't the active state (value) be the same state it was entered and not the one before transitioning?

carlos-sonatafy avatar May 24 '24 19:05 carlos-sonatafy

@crls-dray Would you want something like this?

// PSEUDOCODE
const myAction = assign(({ stateNode }) => {
  console.log(stateNode.id); // e.g. "someMachine.loading"

  return {};
})

davidkpiano avatar May 27 '24 09:05 davidkpiano

Yes, that might work - not sure how'd that translate for parallel states, that's why I thought the actual value would be the same as the snapshot.value. I'm not using parallel states, just mentioning it.


My use-case is that I have an action which is loading some data into the context, and such data is active-state specific.

The statechart is being defined in Stately Studio, the main purpose is to allow non-dev coworkers of mine to model the statechart with minimal overhead due to implementation specifics - thus why I can take away the implementation specifics if I'm able to load the info based on the current/active state.

carlos-sonatafy avatar May 28 '24 18:05 carlos-sonatafy

I have the same use case as @cris-dray. I have a state property in my context loadingStatus.text that I want to be updated every time a state transition occurs.

carlosbensant avatar May 28 '24 22:05 carlosbensant

Based on vck3000's response, I can see this has been the current implementation for a long while, I would like to understand but it doesn't make sense as for me, anytime you add an entry action property to a state, we expect it to match the current state value where the action is placed.

carlosbensant avatar May 28 '24 23:05 carlosbensant

My current implementation looks like this but I have plenty of actions and state transitions (to notify the user, to update timestamp, etc):

import { setup, assign } from 'xstate';

const createDogMachine = (contextFromDB) => {
  return setup({
    actions: {
      updateContext: assign({
        state: (_, params) => params.state,
      }),
    }
  }).createMachine({
    id: 'dog',
    initial: contextFromDB.state || 'asleep',
    context: contextFromDB,
    states: {
      asleep: {
        entry: [
          {
            type: 'updateContext',
            params: {
              state: 'asleep', // current state
            }
          }
        ],
        on: {
          'wakes up': 'awake',
        }
      },
      awake: {
        entry: [
          {
            type: 'updateContext',
            params: {
              state: 'awake', // current state
            }
          }
        ],
        on: {
          'falls asleep': 'asleep',
        }
      },
      //...
    }
  });
}

gist: https://gist.github.com/carlosbensant/21adcd22373d16f1388f283a9b53a17f

carlosbensant avatar May 29 '24 01:05 carlosbensant

cc. @Andarist - I know that you had opinions/thoughts on this

davidkpiano avatar May 31 '24 07:05 davidkpiano

I think giving the user access to the state node that triggers the action would be nice, something like in https://github.com/statelyai/xstate/pull/4217

Andarist avatar May 31 '24 08:05 Andarist

I had the same issue, when trying to access self.getSnapshot().value in an entry action. The documentation is vague, it would be nice if it explicitly specified when these actions are triggered. v4 docs used to say upon entering or exiting a state, which - to me - means the action would be triggered right after entering.

I find that purely from a logical perspective there is an inconsistency between the entry and exit actions in the current implementation.

Entry actions are triggered while outside the target/new state but exit actions are also triggered whilst in the old state. This means that having an exit action on the "old" state (First State in @carlos-sonatafy 's example), is the exact same thing as having an entry action in the "new" state (Second State) if one was to observe self.getSnapshot().value. I think this is pretty strange.

For the time being, I ended up wrapping the body of my action in process.nextTick(() => { ... } to be able to read the entered state with self.getSnapshot().value

balintpeak avatar Apr 22 '25 09:04 balintpeak