Skip to content

Instantly share code, notes, and snippets.

@kiruh
Last active July 14, 2019 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiruh/5738987cae12461eabc6b304ddafa6ea to your computer and use it in GitHub Desktop.
Save kiruh/5738987cae12461eabc6b304ddafa6ea to your computer and use it in GitHub Desktop.
This helper allows you to cancel old api calls, if new one occurs
export class AxiosTokenHelper {
/*
This helper allows you to cancel old api calls, if new
one occurs.
const helper = new AxiosTokenHelper();
const callToApi = async (...) => {
const source = helper.create();
try {
const response = await axios.get(
"/api/endpoint/",
{ cancelToken: source.token },
);
} catch (error) {
// check if cancellation raised the error
if (error instanceof axios.Cancel) return;
}
}
*/
sources = [];
create() {
// cancel and erase old
this.sources.forEach(src => {
src.cancel();
});
this.sources = [];
// create new
const source = axios.CancelToken.source();
this.sources.push(source);
return source;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment