'How to invoke a machine with context of the machine that invokes that machine?
Firstly, here’s the code. I need to fix.
Basically, there are two machines:
currentStateMachine:- currently, I want to change the state manually (running
sendcommands) 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
contextto store the current timestamp and the state; - PROBLEM: how to invoke
intervalsMachinewith thecontextofcurrentStateMachine? - QUESTION: will
currentStateMachinewait forinvokecompletion before accepting another state event? Or will it wait until the state is processed and only after that a new event is processed?
- currently, I want to change the state manually (running
intervalsMachine:- it creates an interval from the current states whenever a new state is received;
- it uses
contextto storestartTimeof the interval, itslengthand the state during this interval; - the interval calculation is simplified for demostration, in will be much more complex.
TL;DR
How to invoke
intervalsMachine(invoked machine) with thecontextofcurrentStateMachine(machine that invokesintervalsMachine)?Will
currentStateMachinewait forinvokecompletion before accepting another state event? Or will it wait until the state is processed and only after that a new event is processed?
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
