Description
In the docs, it says that actors must always be spawned within an assign call.
When we have a hierarchy like this grandParentMachine => parentMachine => childMachine and our grandParentMachine wants to spawn the parentMachine + it's child machine, should it be allowed to spawn the child straight into the parent actors context within a single assign call?
entry: assign({
parentRef: () =>
spawn(
parentMachine.withContext({
childRef: spawn(childMachine)
})
)
})
Alternatives
In this simple example, it'd be pretty straightforward to spawn the childRef within an entry action of the parentMachine, however if the grandParentMachine fetches data for both the parent and child machine, the situation gets more tricky.
We can put the parentMachine into an initial state where it waits for an event to spawn its child actor. Needs extra event from parent to child + extra state.
When spawning the parentMachine, also dump the fetched child data into its context. The parent machine can pick up the child actor state in an entry action, remove it and instead pass it to the withContext call when spawning the child actor.
entry: assign({
childRef: (context) => spawn(childMachine.withContext(context.childData)),
childData: undefined,
}),
Expected Result
Not sure what the best solution here is. Should XState be aware of the context hierarchy when an actor gets spawned to assign the correct parent service or should I use solution (1) / (2) instead?
Actual Result
As the docs already kind of suggested, this doesn't work at the moment. Everything seems to work fine until the childMachine uses sendParent. Expectedly, it sends events straight to the grandParent instead of the "hierarchical-correct" parent actor.
Reproduction
I can commit the test I wrote when trying it out for reference and future discussions.
I believe the 2nd mentioned option is the most idiomatic one. Only a parent can start its children in the actor model, this shouldn't be bypassed anyhow as an actor keeps track of a child lifecycle (to some extent) etc.
Perfect, thank you for the quick reply 馃槉
Most helpful comment
I believe the 2nd mentioned option is the most idiomatic one. Only a parent can start its children in the actor model, this shouldn't be bypassed anyhow as an actor keeps track of a child lifecycle (to some extent) etc.