1

I'm trying to understand Actors to be able to pass data from a sibling component to another.

I have these machines: parent and child. parentMachine sends a GET event to childMachine in the success transition. Once childMachine receives an event.value it should be assigned to a user property in its context.

const [currentChild, sendChild] = useMachine(childMachine);

Now, when I log currentChild.context after clicking fetch, the user property is empty. How do I use the data received from parentMachine in a component that depends on childMachine?

CodeSandbox: https://codesandbox.io/s/patient-frost-9lxoh

const parentMachine = Machine({
  id: "parent",
  initial: "idle",
  context: {
    ref: undefined
  },
  states: {
    idle: {
      on: {
        FETCH: {
          target: "loading"
        }
      }
    },
    loading: {
      invoke: {
        id: "getUser",
        src: (_, event) => fetchUser(event.value),
        onDone: {
          target: "success",
          actions: assign({
            user: (_, event) => {
              return event.data;
            }
          })
        },
        onError: {}
      },
      entry: assign({
        ref: () => spawn(childMachine)
      })
    },
    success: {
      entry: (ctx, evt) => ctx.ref.send({ type: "GET", value: ctx.user })
    },
    failure: {} 
  }
});

const childMachine = Machine(
  {
    id: "child",
    initial: "waitingForData",
    context: {
      user: []
    },
    states: {
      waitingForData: {
        on: {
          GET: {
            actions: [
              assign({
                user: (ctx, evt) => [...ctx.user, evt.value]
              }),
              "logger"
            ]
          }
        }
      }
    }
  },
  {
    actions: {
      logger: ctx => console.log(ctx.user)
    }
  }
);
Ivor
  • 590
  • 6
  • 21

1 Answers1

0

For doing that you can invoke Promises, Callbacks, Observables and Machines, as mention here, when you invoke machines you have to wait until invoked machine reaches its final state, and you will receive the result in the onDone, and when you invoke a Promise you have to wait until it finishes and you will receive the result in the onDone too.

Here you go an example of invoking a Machine and a Promise.

luisbar
  • 676
  • 5
  • 11