Have an xstate machine receive an event and update context(but not change state) regardless of which state it's in

3.1k views Asked by At

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.

1

There are 1 answers

0
Jared Smith On BEST ANSWER

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.