In ReactJs I am using Axios to getting data from API. I need to use cancelToken when I try to make the duplicate requests. E.g: suppose I am on the homepage before complete Axios request, I am requested for About page. As a result, the React app showing memory leaking error. So, my plan is to set Axios cancelToken in Axios interceptors. I have tried but, it is not working for me.
requestApi.js
import axios from 'axios';
const requestApi = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
const source = axios.CancelToken.source();
requestApi.interceptors.request.use(async config => {
const existUser = JSON.parse(localStorage.getItem('user'));
const token = existUser && existUser.token ? existUser.token : null;
if (token) {
config.headers['Authorization'] = token;
config.headers['cache-control'] = 'no-cache';
}
config.cancelToken = source.token;
return config;
}, error => {
return Promise.reject(error);
});
requestApi.interceptors.request.use(async response => {
throw new axios.Cancel('Operation canceled by the user.');
return response;
}, error => {
return Promise.reject(error);
});
export default requestApi;
Dashboard.js
import requestApi from './requestApi';
useEffect(() => {
const fetchData = async () => {
try {
const res = await requestApi.get('/dashboard');
console.log(res.data);
} catch (error) {
console.log(error);
}
}
fetchData();
}, []);