Skip to content
the poor coder

how to when send a new request i can abort last request in axios next js

Poor Man
Published
Reading time
2 min read
On this page

How to Abort Last Request in Axios Next.js#

If you are working with Axios in Next.js and want to send a new request while aborting the previous one, there are a few ways to do it. Here's what worked for me:

Using Axios Cancel Token#

The first approach is to use the Axios cancel token. This allows you to cancel a request before it is completed. Here's how you can do it:

Text

import axios from 'axios';
import { CancelToken } from 'axios';

let cancel;

const sendRequest = async () => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1', {
      cancelToken: new CancelToken(function executor(c) {
        // An executor function receives a cancel function as a parameter
        cancel = c;
      })
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};

// Send the first request
sendRequest();

// Send a new request and cancel the previous one
cancel();
sendRequest();

In this example, we create a new instance of the CancelToken class and pass an executor function that receives the cancel function as a parameter. We store this function in a variable named "cancel". When we want to abort the previous request, we simply call this function.

Using Axios Interceptors#

The second approach is to use Axios interceptors. Interceptors are functions that Axios calls for every request and response. They can be used for various purposes, such as modifying headers or handling errors. In our case, we can use an interceptor to cancel the previous request before sending a new one. Here's how:

Text

import axios from 'axios';

let cancel;

// Add a request interceptor
axios.interceptors.request.use(function(config) {
  // Cancel the previous request
  if (cancel) {
    cancel();
  }

  // Create a new CancelToken
  config.cancelToken = new axios.CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  });

  return config;
});

const sendRequest = async () => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};

// Send the first request
sendRequest();

// Send a new request and cancel the previous one
sendRequest();

In this example, we add a request interceptor that checks if there is a previous request and cancels it using the cancel function. We also create a new instance of the CancelToken class and store the cancel function in a variable named "cancel". Finally, we set the cancel token in the request configuration. Now, every time we send a new request, the interceptor will cancel the previous one.

Both approaches have their pros and cons, so choose the one that fits your needs best. Using cancel tokens gives you more control over when to cancel a request, while using interceptors automates the process for you.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC