React Cancel all axios request in componentWillUnmount.
By: Juliet Onyekaoha
Tags: React, Componentwillunmount, Abortcontroller, Cancel Request, Axios

The code for this article is in this codesandbox, If you don’t need explanations as to why things are happening, head over there, otherwise keep reading, I promise you will learn a thing or two.

Why Cancel Requests?

It is one thing to write an asynchronous call to an API to fetch data, and it is another thing to cancel that call when it is not beneficial to our users. The single action of cancelling API request when it is no longer needed leads to a better performant app devoid of bugs. A common scenario where an API request needs to be cancelled is when a user navigates away from a page.

Let’s say you have a React app that makes several calls once the component mounts inside the componentDidMount lifecycle of a component, if a user navigates to that page, the API requests starts, however, if the user navigates away from that page before the request is completed, by default the API requests still runs in the background and if possible updates different parts of your application that need that data even though at that point the user no longer needs (because they are on another page) the data that is returned from the request.

At the point the user navigates away from the page, all API requests made in it to update the state and render a view with the data is unnecessary and if not cancelled leads to memory leaks in an application. React alerts us to this problem by outputting these popular lines in the console

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

in Landing (created by Context.Consumer)

How cancelling requests works in axios

To start the process of cancelling an axios request, the following steps are involved:

Create a variable that will hold the cancel token source

let source = axios.CancelToken.source(); Inside the axios request config, pass the token of the created source variable as the value of the cancelToken key/property.

let config = { cancelToken: source.token}

axios.get(endpointUrl, config).then((res) => {})

or

axios.get(endpointUrl, { cancelToken: source.token}).then((res) => {}) Trigger the cancel request by calling source.cancel() where and when (in a react component this can be on the componentWillUnmount lifecycle method or on the click of a button) you need to cancel the request. Catch the error being thrown (an error is thrown in every cancel request) inside the catch block of the axios request.

The entire axios cancel request API is built on top of the DOM AbortController API that is used to abort/terminate all asynchronous actions in a program. To use it:

Instantiate a new controller object

const controller = new AbortController();

Then create a signal that alerts the async action on when to terminate/abort its process. In case of a network request, this will signal the request to cancel.

const signal = controller.signal;

Pass the signal to the action. For e.g, a fetch request has a signal property on its config object that accepts an AbortSignal.

fetch(url, { signal: signal}).then(res => {})

Call the abort property on the AbortController object to abort the request.

controller.abort();

For practical code examples of how to use the AbortController API refer to this article.

How to Cancel Requests where the Axios request is inside the component.

Both the axios request and cancel request happens is handled inside this component

Steps involved: