Using actors with XState to implement a <form>
to upload a file (<input>
with type="file"
).
The logic to upload the file is separate inside upload-file-machine.ts
. This machine is only responsible to handle file inputs.
It implements the following events:
file.upload
: when a user selects a file from theinput
file.remove
: allows to remove the current uploaded file
This machine (actor) has a single responsibility: upload the file.
It then interacts with another parent actor that is responsible to submit the form.
A reference to the parent actor is provided as input to the machine (parentId
of type AnyActorRef
).
The child machine notifies the parent by sending shared events (UploadFileEvent
events sent using sendTo
).
Parent machine
The form-machine.ts
stores a reference to the child inside its context
(uploadImage
of type ActorRefFrom<typeof UploadFileMachine.machine>
).
When the machine starts, an instance of the child machine is spawned inside context
using spawn
.
The parent provides an instance of itself as input to the child (
self
).
It will then respond to the events from the child actor and store the imageUrl
sent by the child.