Hi there! This technique is relevant only for fetch, React, and Redux-Saga libraries. The problem's solution has practical application. Suppose we want to send a large file to the server, but the user unexpectedly decides to cancel the upload. It means that we need to stop the process of uploading data to the server.
First, we need to determine the starting point for our saga. Then create an infinite loop. Next, fork file upload worker. The purpose is to keep the worker linked and continue running without waiting for it to complete. Here we use takeEvery, for each abort action, we call the abort worker and pass it forked upload worker as a param.
Saga worker to abort a file upload.
We should use the AbortController object to abort requests. First, create a new AbortController instance (Line 4). Next, pass it as an additional signal parameter to fetch. (Line 10). Upload success or error is handled like in normal saga flow. We are interested in the "finally". This section is executed in any case. So, here we monitor whether the task was interrupted. If so, then the request to the server should be aborted with the abort method (Line 19). That's it.
This simple technique solves such non-trivial and important task of interrupting requests to the server. Note that we used fetch, while XMLHttpRequest has its own abort mechanism.
If my story was interesting, you found a mistake, or disagree with something, please feel free to drop me a message. My contacts are at the top of the page 😉