How to cancel axios requests

There may come a time where you have to cancel a network request as you no longer care for handling the response. An example of this might be a search input, if the user changes the search query before a response has been returned from the server then we can safely cancel the request and issue a new request with the updated search query.

To do this with axios we can use cancel tokens. We first need to ask for a cancel token which we then pass to axios when making a request.

import Axios, { CancelToken } from "axios";

const source = CancelToken.source();
Axios.get("https://pokeapi.co/api/v2/pokemon/ditto", {
  cancelToken: source.token,
});

Now we can use our source.token to cancel the request if needed by calling the cancel method on the token object.

source.token.cancel();

Matthew Henley

🖥 Software engineer. React, Elm and Elixir enthusiast 🐣