statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
27.17k stars 1.26k forks source link

[4.9] stateGuard state for choose action creator #1144

Closed CodingDive closed 4 years ago

CodingDive commented 4 years ago

Hey, I've just started playing with the new choose action creator. Amazing job @Andarist and @davidkpiano. I just saw the tests and was amazed to see even nested choose actions work. 🔥

Description It would be very nice to pass the whole guardMeta object, including the state to the conditional expressions of the choose action creator.

entry: choose([
  {
    // state is undefined :(
    cond: (_, __, { state }) => state.matches('bar'),
    actions: assign<Ctx>({ answer: 42 })
  }
])

Expected Result

Passing the current state on top of context and event.

Actual Result

The third argument of the condition expression callback already exists.

When I log the stateGuard, this is what I get:

cond: {
  type: "xstate.guard",
  name: "isPasswordResetMode",
  predicate: Æ’ (context, event, stateGuard), // <-- how do I get to this?
}

However, state is undefined.

Reproduction

I will send a PR with a failing test.

Considerations

I'm not sure if this is SCXML compatible but since any choose action can be translated to a regular state transition with normal guards, this shouldn't be a problem right?

Additional context XState 4.9.1

davidkpiano commented 4 years ago

Great that you're playing around with it! By the way, for your specific example, there might be a better way to model it. You shouldn't use state.matches() in a guard function - that function should be part of the matched state naturally.

CodingDive commented 4 years ago

@davidkpiano I very rarely have the need to use state.matches in a guard. When I do, it's typically to check the machine state of orthogonal nodes. Is there a better way to do this?


Closing this issue. stateGuard.state is not available during the initialization of the machine. It should work right after. See the discussion here.

davidkpiano commented 4 years ago

Is there a better way to do this?

Yes, using in: https://xstate.js.org/docs/guides/guards.html#in-state-guards

Remodeling might also help.

FadySalama commented 1 year ago

Is there a better way to do this?

Yes, using in: https://xstate.js.org/docs/guides/guards.html#in-state-guards

Remodeling might also help.

Is it possible to us the in predicate in choose action? If not, would it be possible to add it as a feature?

davidkpiano commented 1 year ago

@FadySalama Can you ask this in a discussion? https://github.com/statelyai/xstate/discussions/new