Skip to content

Commit 683247a

Browse files
committed
invoke.mdx: Sending Responses
1 parent ba15efc commit 683247a

File tree

1 file changed

+83
-1
lines changed

1 file changed

+83
-1
lines changed

docs/invoke.mdx

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -596,7 +596,89 @@ _Coming soon_
596596

597597
## Sending Responses
598598

599-
_Coming soon_
599+
An invoked actor (or [spawned actor](./spawn.mdx)) can _respond_ to another actor; i.e., it can send an event _in response to_ an event sent by another actor. To do so, provide a reference to the sending actor as a custom property on the event object being sent. In the following example, we use `event.sender`, but any name works.
600+
601+
```js
602+
// Parent
603+
actions: sendTo(
604+
'childActor',
605+
({ self }) => ({
606+
type: 'ping',
607+
// highlight-next-line
608+
sender: self
609+
})
610+
);
611+
612+
// Child
613+
actions: sendTo(
614+
// highlight-next-line
615+
({ event }) => event.sender,
616+
{ type: 'pong' }
617+
)
618+
```
619+
620+
In the following example, the `'client'` machine below sends the `'CODE'` event to the invoked `'auth-server'` service, which then responds with a `'TOKEN'` event after 1 second.
621+
622+
```js
623+
import { createActor, createMachine, sendTo } from 'xstate';
624+
625+
const authServerMachine = createMachine({
626+
id: 'server',
627+
initial: 'waitingForCode',
628+
states: {
629+
waitingForCode: {
630+
on: {
631+
CODE: {
632+
// highlight-start
633+
actions: sendTo(
634+
({ event }) => event.sender,
635+
{ type: 'TOKEN' },
636+
{ delay: 1000 }
637+
)
638+
// highlight-end
639+
}
640+
}
641+
}
642+
}
643+
});
644+
645+
const authClientMachine = createMachine({
646+
id: 'client',
647+
initial: 'idle',
648+
states: {
649+
idle: {
650+
on: {
651+
AUTH: { target: 'authorizing' }
652+
}
653+
},
654+
authorizing: {
655+
invoke: {
656+
id: 'auth-server',
657+
src: authServerMachine
658+
},
659+
// highlight-start
660+
entry: sendTo(
661+
'auth-server',
662+
({ self }) => ({ type: 'CODE', sender: self })),
663+
// highlight-end
664+
on: {
665+
TOKEN: { target: 'authorized' }
666+
}
667+
},
668+
authorized: {
669+
type: 'final'
670+
}
671+
}
672+
});
673+
```
674+
675+
That specific example could be simplified by using the `sendParent(...)` action creator for the same effect. But by using `sendTo` the actors do not strictly need to be in a direct parent-child relationship to communicate.
676+
677+
Note that by default `sendTo` will send events anonymously, in which case the reciever will not know the source of the event.
678+
679+
:::note
680+
In XState v4, the `respond(...)` action creator was used for this purpose. In XState v5, use `sendTo(...)` instead.
681+
:::
600682

601683
## Multiple Actors
602684

0 commit comments

Comments
 (0)