2

Basically, I have a bunch of different states. I want the machine to be able to receive and update context externally via an event(regardless of which state it's in). I found this link saying how events can be root level... Using xstate, is it possible to configure an event that is applicable under all states and is handled in the same way across all states and substates?

But I also seem to remember how new assigns() don't actually take effect until the state changes.

Jared Smith
  • 283
  • 4
  • 11
  • What do you mean by _"take effect"_? Are you expecing a service to be invoked? Or a subscriber to be notified of contextual state changes? – chautelly Nov 29 '20 at 18:21
  • I basically wanted to be able receive an event in any state, and have the context updated by the event, and accessible in that state, without additional state changes. – Jared Smith Dec 08 '20 at 02:28

1 Answers1

8

I don't know that it's documented anywhere, but a seemingly good solution I learned about from the xstate forums was doing a top level transition.

{
  initial: 'Idle',
  on: {
    NEW_BLOCK: {
      actions: assign({
        block: 'addNewBlock'
      }),
      internal: true,
    },
  },
  states: {
    Idle: {},
    StateOne: {},
    StateTwo: {},
  }
}

That will cause the entire machine to always be watching for the 'NEW_BLOCK' event, and will add it to context, regardless if the event arrives during Idle, StateOne, StateTwo, or any other states you may add. It will cause a Self Transition for whichever state the machine is in. But the updated context will be immediately available afterwards.

mihi
  • 3,097
  • 16
  • 26
Jared Smith
  • 283
  • 4
  • 11