5

I need send event to another spawned state machine that its ID I have as a string in a variable in the context. (it is not parent state machine and not child)

Like

context.sendTo = 'B_id'

how to do send() with parameter from context?

and how to put send('MY_EVENT_NAME', {to: <something from context> }) in the MachineOptions actions section?


// this does not work...
const myMachineOptions:Partial<MachineOptions<any,any>> = 
{
  actions:{
     mySend: (context, event)=>send('MY_EVENT_NAME', {to: context.sendTo })
  }
}

P.S.

it like in the Pass values when sending events from one machine to another in xState

but what I need to by dynamic is not the message body but the to: part

Boris Daich
  • 2,431
  • 3
  • 23
  • 27

1 Answers1

5

following the help from the developers of the XState https://github.com/davidkpiano/xstate/issues/1110

actions {
    actionSendMyEvent: 
             send('MY_EVENT_NAME', { to: context => context.sendTo })
    }

Huge thanks to the XState developers and maintainers!!!

Boris Daich
  • 2,431
  • 3
  • 23
  • 27
  • It would nice to understand why your original solution did not work. – monzie May 07 '20 at 23:20
  • 1
    @monzie I believe the original solution does not work because `send` is an "action creator" and does not imperatively send the event. See the documentation on the send action: https://xstate.js.org/docs/guides/actions.html#send-action (and specifically the warning in that section). You'll notice that the working examples in the documentation take the form of OP's answer as opposed to in his question where the action is a function that returns the result of the `send` action creator. – Jon Rubins May 10 '20 at 23:23
  • Thanks for the questions and answers here @Boris and @Jon. I'm struggling with this setup in a Vue app. I have an `alert-machine` that's instantiated when I start my app. It's a simple machine that I send user notifications too. When I create machines in other files/components Im not sure the best way of sending events to the alert machine as it's already a running service. Do I import the service into other machines? I tried `send('ALERT', { to: 'alert', alert: 'TEST' })` and I get `Unable to send event to child 'alert' from service`. How does a machine send events to another running service? – Giles Butler Jun 03 '20 at 19:58
  • I have the same problem, did you solve it somehow? – user9547708 Dec 23 '20 at 21:06