Last active
July 14, 2019 15:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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