1

Firstly, here’s the code. I need to fix.


Basically, there are two machines:

  • currentStateMachine:
    • currently, I want to change the state manually (running send commands) once a second based on the real state;
    • later, it might be better to run a callback function based on which the state would change, however, currently I have no idea if it could work like that;
    • I use context to store the current timestamp and the state;
    • PROBLEM: how to invoke intervalsMachine with the context of currentStateMachine?
    • QUESTION: will currentStateMachine wait for invoke completion before accepting another state event? Or will it wait until the state is processed and only after that a new event is processed?
  • intervalsMachine:
    • it creates an interval from the current states whenever a new state is received;
    • it uses context to store startTime of the interval, its length and the state during this interval;
    • the interval calculation is simplified for demostration, in will be much more complex.

TL;DR

  1. How to invoke intervalsMachine (invoked machine) with the context of currentStateMachine (machine that invokes intervalsMachine)?

  2. Will currentStateMachine wait for invoke completion before accepting another state event? Or will it wait until the state is processed and only after that a new event is processed?

Acorn
  • 49,061
  • 27
  • 133
  • 172
tukusejssirs
  • 564
  • 1
  • 7
  • 29

1 Answers1

1

You can use the data property with invoke to specify context to be taken from the parent.

const timerMachine = createMachine({
  id: 'timer',
  context: {
    duration: 1000 // default duration
  }
  /* ... */
});

const parentMachine = createMachine({
  id: 'parent',
  initial: 'active',
  context: {
    customDuration: 3000
  },
  states: {
    active: {
      invoke: {
        id: 'timer',
        src: timerMachine,
        // Deriving child context from parent context
        data: {
          duration: (context, event) => context.customDuration
        }
      }
    }
  }
});

https://xstate.js.org/docs/guides/communication.html#invoking-with-context

Another option is you can use the (ctx, evt) => ... pattern for the src option.

Acorn
  • 49,061
  • 27
  • 133
  • 172