I am trying to cancel the fetch calls using the AbortController. This is what my API extraction looks like. I have a function that handles both get and post calls and these get and post methods and extracted out separately as well.
export async function customAjax(options){
let options = {};
options.headers = { ...options.headers, ...obj.headers };
const response = await fetch(url, options);
await response.json()
}
const get = (url, extra = {}) => api({ url, type: "GET", ...extra });
const post = (url, payload, extra = {}) => api({ url, data: payload ,type: "POST",
}, ...extra });
const api = async (payload) => {
try {
promise = customAjax(payload);
const response = await promise;
if (response && !errorMessage) {
return { response, error: false, loading: false, request: promise };
} else if (errorMessage) {
return { response: false, error: "Error", loading: false, request: promise };
}
}
catch (e) {
return { response: false, error: "Error", loading: false, request: promise };
}
return { response: false, error: false, loading: true, request: promise };
}
So from respective components, I will be calling get or post methods.
function MyComponent(){
useEffect(() => {
makeCall();
saveResponse();
}, []);
async function makeCall(){
const { response, error } = await post(URL, payload);
// Handling code is not added here
}
async function saveResponse(){
const { response, error } = await get(URL);
// Handling code is not added here
}
}
As you see this is a component where I call both the methods. I basically want to cancel the calls when moving away. What is ideal way to create a abort instance and pass it? How do I achieve with my current API structure. Some pointers would help and appreciated