Aborting Web Requests
Today, we will see how to cancel web requests with the AbortController API.
It is essential to know this since, on many occasions, we will have specific components that will be disassembled from our application and that have pending requests. If we do not cancel them, they will remain in the background even though the information they return is no longer of interest to us or we need it.
If we don't know this, we could have memory leaks and race conditions in the apps, as it happens in many applications that do not consider it.
Abort web requests when appropriate
You can create a new AbortController object using the AbortController() constructor.
By using an AbortSignal object, you can communicate with a DOM request.
Let's see an example in React:
Let's explain it:
Create an instance of AbortController and extract the signal property.
You make an API call and add that signal to the fetch.
The key is in the cleanup function of useEffect. You abort the request (π€π°π―π΅π³π°πππ¦π³.π’π£π°π³π΅()) when the component unmounts.
If you use external libraries such as React Query or SWR, you must check out how it's handled in each.
In React Query, Here's how to do it in useQuery if you use fetch:
The query will be cancelled (e.g. aborting the fetch) when you've started receiving a query, but then unmount the component before it finishes. Cancelling the query will result in its state beingΒ revertedΒ to its previous state.
Conclusion
You have to handle web requests through the AbortController API when needed. You will avoid unwanted issues in your apps. It's straightforward to do it with the API using fetch API and in third libraries like React Query.
Here, I share 2 helpful resources that also talks about this topic. I strongly recommend it:
https://developer.mozilla.org/en-US/docs/Web/API/AbortController
https://tanstack.com/query/v4/docs/react/guides/query-cancellation
I hope you enjoyed the article.
Join the weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!