Xstate: Invoked machines with data wipe out child machine's context

Created on 11 Feb 2020  路  2Comments  路  Source: davidkpiano/xstate

Description
When you invoke a machine with context: e.g. parent -> child, and the parent needs to pass down a piece of context, you can use data to do that.

However, what if the child has its own context it needs to keep track of? It appears that when using data to invoke the child machine, it completely wipes the child machine's context and it only has the context provided by the parent.

Expected Result
Invoking a child machine while using data should add to the child machine's context, not overwrite it.

Actual Result
Invoking a child machine while using data overwrites all values of the child's context.

Reproduction
https://xstate.js.org/viz/?gist=2740527eeb35dd946e6b711f1c76f7e7

open the console and see the context: {} is logged with only the context that was assigned by the parent, and the child's other context items were wiped out.

Additional context
n/a

bug has workaround

Most helpful comment

This is currently "by design" but the way that context will work in V5 is by shallow merging, so you won't have this problem.

All 2 comments

Here is my solution:

/* some must-have import */
import childMachine from './childMachine'

const parentMachine = {

   /* some other machine config */

   states: {
     invokingChildMachineState: {
        invoke: {
          id: 'machineId',
          src: childMachine,
          data: context => ({
            ...childMachine.context,
            value: context.value // the value you want to pass to child machine
          })
        }
     }
   }
}

This is currently "by design" but the way that context will work in V5 is by shallow merging, so you won't have this problem.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jfun picture jfun  路  3Comments

mattiamanzati picture mattiamanzati  路  3Comments

carloslfu picture carloslfu  路  3Comments

bradwoods picture bradwoods  路  3Comments

carlbarrdahl picture carlbarrdahl  路  3Comments