Last active
February 18, 2021 13:38
-
-
Save Munawwar/2a9007ae8bc832ecdfc3fa924f4ee826 to your computer and use it in GitHub Desktop.
Axios call that aborts/cancels the previous call automatically
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
const postAndCancelPrevCall = (() => { | |
let cancelTokenInstance; | |
return async (body) => { | |
try { | |
if (cancelTokenInstance) { | |
cancelTokenInstance.cancel('cancelled by user'); | |
} | |
cancelTokenInstance = CancelToken.source(); | |
const axiosResponse = await axios.post(body, { | |
cancelToken: cancelTokenInstance.token | |
}); | |
cancelTokenInstance = null; | |
return axiosResponse; | |
} catch (err) { | |
if (!axios.isCancel(err)) { | |
throw err; | |
} | |
} | |
return undefined; | |
}; | |
})(); | |
Promise.all([ | |
// like a user typing 'hi' on a text field.. | |
postAndCancelPrevCall({ text: 'h' }), | |
postAndCancelPrevCall({ text: 'hi' }), | |
]).then(results => console.log(results)); // [undefined, <axiosResponse>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment