#[v4] Spawn child machine with context from parent

1 messages · Page 1 of 1 (latest)

gloomy briar
#

Hello, i have a parent machine that manages a stepper in UI, this machine will spawn a child machine on every step (state)
i store in the parent machine context some global vars and i would like to pass those values to the invoked child:

Here in parent machine definition i tried using the data property and it works but it overwrite the child machine context

step1: {
      invoke: {
        id: 'step1',
        src: 'step1',
        data: (parentcontext) => parentcontext,
      },
............
  services: {
    // passing react hooks to implement child machine configs
    step1: step1Machine.withConfig(step1Options(intl, addSnackbar)),
................

How can i pass the parent machine context (or some props) without overwriting the child machine context?
Is there a way to merge the two contexts?

Thanks in advance!

spark estuary
#

This is one of the main reasons we introduced input in v5 as an intuitive solution 😅

#

But anyway, you can merge it like this:

step1: step1Machine.withContext({
  ...step1Machine.context, // initial context of machine
  ...yourContext
})
#

You can do a similar thing with .withConfig

gloomy briar
#

Thanks @spark estuary i tried withContext and now the two contexts are merged but it returns the initial values so i ended up with everything equal to undefined

services: {
    step1: step1Machine
      .withContext({
        ...step1Machine.context,
        ...parentMachine.context,
      }).withConfig(step1Options())

This is kinda predictable because the step1Machine and parentMachine are the references of two machines created with createMachine with named services, guards, actions etc...

How can i get the contexts of the running machines please?

spark estuary
#

A machine is not an actor; it's a "blueprint" for a machine. Think of it like a function; it doesn't represent the actual instance