While the order of actions in XState is fairly clear, how assign
s are handled in them is non-obvious.
If you have a scenario where you try and utilize context
in one action, then assign
a new value to context
, and then try and utilize the new context in another action, you'll find that actually both actions received the new context
as their argument. Why does this happen?
This happens because XState.Machine.transition
is a pure function. In order to remain pure, it does not run the actions, it accumulates them into an actions
array that is returned in the next state object. Since transition
does not run any side effects, it must calculate the next context
object and return this on the state object as well. Thus, any action returned is then called in the interpreter with the next context, not the context assumed to exist at the time and order the action was written.