#Getting current machine's context to use in `.bind`

1 messages · Page 1 of 1 (latest)

dense wyvern
#

I have an external function called onMessageUpdated

I need to send events from that function to a child state machine.

Here's how I'm binding that function already in invoked service:

states: {
createThread: {
    invoke: {
      src: "createThread",
      onDone: {
        target: "threadCreated",
        actions: assign({
          threadName: (context, event) => event.data.threadId,
          boundOnMessageUpdated: (context: any, event: any) =>
            event.data.boundOnMessageUpdated,
        }),
      },
      onError: {
        target: "error",
        actions: assign({
          error: (context, event) => event.data,
        }),
      },
    },
  },
}

services: {
  createThread: async (context, event) => {
    const threadId = await createThread(context.threadName);

    return {
      threadId,
      boundOnMessageUpdated: onMessageUpdated.bind(
        null,
        threadId
      ),
    };
  },
}

This machine is spawned from a parent machine. How do send an event from onMessageUpdated? Tried a couple ways:

export const onMessageUpdated = (
    threadId: string,
    oldMessage: Message<boolean> | PartialMessage,
    newMessage: Message<boolean> | PartialMessage
  ) => {
    if (newMessage.channel.id === threadId && newMessage.content) {
      logger.debug('Sending "UPDATED_MESSAGE" event to "messageSequence"');
      // send({
      //   type: "UPDATED_MESSAGE",
      //   payload: {
      //     content: newMessage.content,
      //   },
      // });
      raise<unknown, GenerateMachineEvent>({
        type: "UPDATED_MESSAGE",
        payload: { content: newMessage.content },
      });
      // sendTo()
      // sendTo("messageSequence", {
      // type: "UPDATED_MESSAGE",
      // });
    }
  };
stable kettle
#

This seems pretty custom; what are you ultimately trying to do? What os onMessageUpdated and why does it need to be bound?

dense wyvern
#

I guess the question can be simplified to: how do I send a child machine an event externally?

#

@stable kettle I'm binding it that way because in state X I register onMessageUpdated to handle some events and in state Y I want to unregister it. The handlers require some data from events in those states. Does that make any sense?

dense wyvern
#

Inline-ing the handler doesn't change much:

Also tried sending the parent machine an event..nothing 😦

sendTo("<parent machine id>", {
                type: "GO_TO_LOGIN",
                // payload: { content: newMessage.content },
              });