Are you excited to learn how to cancel Axios requests in Vue.js 2 effectively? In this tutorial, we’ll walk you through the process step by step. By the end of this guide, you’ll be able to cancel ongoing API requests in your Vue.js 2 applications using Axios, improving your app’s performance and user experience.
Step 1: Create the Axios Instance
First, let’s create a custom Axios instance that we’ll use to make our API requests. This instance can include any custom settings or configurations that you may require in your project.
// src/axiosInstance.js import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://your-api-url.com', // Add any other custom settings for your Axios instance here }); export default axiosInstance;
In this code snippet, we create an Axios instance using axios.create()
and set a baseURL
for our API requests. This instance is then exported for use in other parts of our application.
Step 2: Add the Request Cancellation Function
Now, let’s add a function that makes an API request and accepts a cancelToken
as an argument. This token will be used to cancel the ongoing request whenever required.
// src/axiosInstance.js import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://your-api-url.com', }); const fetchDataWithCancellation = (data, cancelToken) => { return axiosInstance.get('/data', { params: data, cancelToken: cancelToken, // Pass the cancelToken to the Axios request }); }; export default { fetchDataWithCancellation, };
Here, we define a fetchDataWithCancellation
function that takes a data object and a cancelToken
. The cancelToken
is passed to the Axios request to enable request cancellation.
Step 3: Implement Request Cancellation in the Vue.js Component
Next, let’s update our Vue.js component to handle request cancellation using the fetchDataWithCancellation
function we defined earlier.
<template> <div> <input type="text" v-model="inputValue" /> <button @click="fetchData">Fetch Data</button> </div> </template> <script> import axios from 'axios'; import { fetchDataWithCancellation } from '@/axiosInstance'; export default { data() { return { inputValue: '', cancelTokenSource: null, }; }, watch: { inputValue(newValue) { if (this.cancelTokenSource) { this.cancelTokenSource.cancel('Axios request cancelled due to inputValue change'); // Cancel the ongoing Axios request this.cancelTokenSource = null; // Reset the cancelTokenSource } }, }, methods: { fetchData() { // Create a new CancelToken source and assign it to the component's data this.cancelTokenSource = axios.CancelToken.source(); fetchDataWithCancellation({ param1: 'value1' }, this.cancelTokenSource.token) .then(response => { console.log(response.data); }) .catch(error => { if (axios.isCancel(error)) { console.log('Axios request cancelled:', error.message); } else { console.error('Error fetching data:', error); } }); }, }, }; </script>
In this Vue.js component, we:
- Import the
fetchDataWithCancellation
function from our custom Axios instance. - Define a watcher for the
inputValue
data property. If