Hello guys ! 👋
Today, let's take a look at cancelling a web request with fetch and Abort Controller in React Hooks! 🤗
When we work with Fetch to manage data, we sometimes want to cancel the request (e.g. when we leave the current page, when we leave a modal, ...).
In the example below 👇, we fetch the data to display when switching route. But, we leave the route/page before the fetch is completed.
We just saw a memory leak in action! 💪🏼 Let’s see why this error occurred, and what it exactly means.
❓ WHY A MEMORY LEAK?: We have a component that performs an asynchronous
fetch(url) task, then updates the state of the component to display the elements, BUT we unmount the component before the request is even completed. The state of the unmounted component is updated (e.g.
setState), which follows a memory leak.
Abort Controller allows you to subscribe to one or more Web Requests with the ability to cancel them. 🔥
First of all, let's create a new AbortController object instance.
Now, we can access to
Let's see how to use it 💪
And finally, if we want to cancel the current request, just call
abort(). Also, you can get
controller.signal.aborted which is a
Boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false).
❗️ Note: When
abort()is called, the
fetch()promise rejects with a
Yeah, you just learned how to cancel a Web Request natively! 👏
Below is an example of a component that retrieves data in order to display them:
If I leave the page too fast and the request is not finished: MEMORY LEAK
useEffect to subscribe to our
fetch request and to avoid memory leaks. We use the clean method of
useEffect for calling
abort() when our component unmount.
Now, no more memory leaks! 😍
As always, feel free to reach out to me! 😉
Cheers 🍻 🍻 🍻