我已经为API服务创建了一个公共axios请求文件,一个公共函数getRequest(URL)
在需要的地方被调用。
我想实现的是,每当新请求被调用/触发时,以前的请求应该被取消。
这是我已经尝试过的,但它并没有像预期的那样工作。
// My component Users.js
async function getUsers(url) {
try {
const response = await getRequest(url);
// further process with the response
} catch (error){
// handling error here
}
}
useEffect( ()=>{
// URL is getting form endpoints constnats
getUsers(URL);
},[]);
// --------------- end of my component ---------------
//axiosClient.js
import axios from 'axios';
import { BASEURL } from '../config/endpoints';
import { getToken } from '../Auth';
const CancelToken = axios.CancelToken;
export function getRequest(URL, payload={}, headers={}) {
return apiRequest(URL, payload, "get", headers);
}
export async function apiRequest(endPoint, data, method, headers, requestOptions = {}) {
return new Promise(async (resolve, reject) => {
const token = getToken();
const headers = {
Accept: 'application/json',
};
if (data instanceof FormData) {
headers['Content-Type'] = 'multipart/form-data';
} else {
headers['Content-Type'] = 'application/json';
}
if (token) {
headers['access_token'] = token;
}
axios({
method: method,
url: endPoint,
headers:headers,
data: data,
cancelToken: new CancelToken(function executor(c) {return c;})
}).then((result) => { return resolve(result); }).catch((error) => {return reject(error);});
return false;
});
}
// --------------- end of axios client ----------------
1条答案
按热度按时间92dk7w1h1#
我终于找到了解决办法。