I'm trying to find a way to cancel axios requests if another request happens before the first request is complete.
I want it to work as a function. I have made a function looking like this:
import axios from "axios";
async function paginatedActivities(pageNumber) {
let controller = new AbortController();
try {
const fetchData = await axios.get(
`${process.env.SERVERBASEURL}/activities/paginatedactivities`,
{
signal: controller.signal,
params: { query: "query", pageNumber: pageNumber },
withCredentials: true,
}
);
return fetchData.data;
} catch (err) {
console.log(err);
if (axios.isCancel(err)) console.log("request cancelled");
}
}
export default paginatedActivities;
I can't figure out when to call "controller.abort()"..
The function could potentially be called again before it has done its job, and in such cases i'd need it to abort.. any suggestions? (without using the "useEffect"-hook..)
Make the controller a global variable so you can access it between calls of the function
let controller;
async function paginatedActivities(pageNumber) {
if (controller) controller.abort();
controller = new AbortController();
// Make the request
controller = undefined; // Reset the variable so it's not aborted next time
}