I have a simple page on my page I have a function that calls the api. This function did not disappear when I changed the page and it calls the api method again
myFunction
async getFlights() {
try {
const { data } = await this.$axios.get(
`/api/v1/flights/${this.flightIndexResponse.index}`,
);
this.filterResult = [];
this.loadingFlights = false;
this.flightResponse = data?.data?.items;
} catch (e) {
if (e?.response?.data?.code === 418 && this.teapotErrorCounter < 10) {
setTimeout(() => {
this.getFlights();
}, 2000);
} else {
this.reponseStatus = false;
this.flightResponse = [];
this.reponseStatus = false;
this.loadingFlights = false;
}
}
}
when server response with status code 418 . this function run again . and when I change the route did'nt destroy the function
CodePudding user response:
The setTimeout
function adds a callback execution to a distinct queue for the process to execute later.
So even if you change the page and the component gets destroyed, the setTimeout
callback is still there (all the code is still loaded, it's just the Vue component instance that is gone)
Several possible solutions here but I'd advise you to cancel the setTimeout on page change.
vue-router
exposes several hooks (called navigation guards) to listen on page changes:
retryTimeout: null,
[...]
if (e?.response?.data?.code === 418 && this.teapotErrorCounter < 10) {
this.retryTimeout = setTimeout(() => {
this.getFlights();
}, 2000);
}
[...]
beforeRouteLeave() {
// when leaving the page
clearTimeout(this.retryTimeout)
}