how to when send a new request i can abort last request in axios next js
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:
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:
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.