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

Viewed 1645
1 Answers

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.

Related