1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    How Action Order Affects Assigns to Context in a XState Machine

    xstateXState
    >=4.6.7

    While the order of actions in XState is fairly clear, how assigns 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.