Cancelling an axios request from within machine #4691
bflemi3
started this conversation in
Show and tell
Replies: 1 comment
-
Cleaner than what I was going to do! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Looking through the interwebs on best practices for cancelling a request in xstate v5 yielded nothing of note... so I thought I'd post a new discussion on how I accomplished this task. Feedback is welcome!
I'm currently using
[email protected]
.My use case
Users upload documents to our system. Each document is uploaded as a multipart upload to AWS S3 via a signed URL, retrieved from our API. The user can cancel the uploading process at anytime, for any document. When the user cancels the upload process, if the file is currently being uploaded, the multipart upload requests need to be aborted. Pretty standard stuff...
How?
I found a ton of examples on how to abort requests in xstate v4, but nothing on how to do this in v5. Here's how I did it...
Create the
AbortController
in the context of the MachineEach document upload machine is responsible for instantiating their own
AbortController
and sending it to theupload
actor in theuploading
state. The request abort occurs upon exit of theuploading
state. In this way, if there's a transition out of theuploading
state for any reason, the upload is aborted. This simplifies the cancellation of the upload process, and decouples thecancelling
state so that it's solely responsible for notifying the parent (the machine that manages all the document uploads) that it needs to be stopped.For brevity, I'll show the relevant parts of the machine.
documentUploadMachine.ts
Use the
AbortController
in theupload
actorThe abort controller is passed to the
upload
actor. I use[email protected]
, but this could be done with any library (including thefetch
API) that consumes theAbortController
. Again, for brevity I'll only add the relevant parts../actors/upload.ts
./utils/uploadPart.ts
The architected solution above works well for my use case. It may not for yours.
My intent was to have a request cancellation solution for xstate v5 published for others to find and adapt to their use case. I welcome feedback, criticism and questions 🙏
Beta Was this translation helpful? Give feedback.
All reactions