Abort Property
Learn how to make request cancellation functionality cleaner and concise using the abort property.
We'll cover the following...
How to use the abort property
In this example, we have to modify the main api
function in the api/api.js
. Inside it, we’ll create a new function called withAbort
and then use it to wrap all API methods that are returned from the api
function.
Press + to interact
// api/api.js// ...other codeconst getCancelSource = () => axios.CancelToken.source()// Main api functionconst api = axios => {const withAbort = fn => async (...args) => {const originalConfig = args[args.length - 1]// Extract abort property from the configlet {abort, ...config} = originalConfig// Create cancel token and abort method only if abort// function was passedif (typeof abort === 'function') {const { cancel, token } = getCancelSource()config.cancelToken = tokenabort(cancel)}try {// Spread all arguments from args besides the original config,// and pass the rest of the config without abort propertyreturn await fn(...args.slice(0, args.length - 1), config)} catch (error) {// Add "aborted" property to the error if the request was canceleddidAbort(error) && (error.aborted = true)throw error}}return {get: (url, config = {}) => withAbort(axios.get)(url, config),post: (url, body, config = {}) => withAbort(axios.post)(url, body, config),patch: (url, body, config = {}) => withAbort(axios.patch)(url, body, config),delete: (url, config = {}) => withAbort(axios.delete)(url, config),};};
The withAbort
function
The withAbort
function does a similar thing as abortable
...