...

/

Abort Property

Abort Property

Learn how to make request cancellation functionality cleaner and concise using the abort property.

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 code
const getCancelSource = () => axios.CancelToken.source()
// Main api function
const api = axios => {
const withAbort = fn => async (...args) => {
const originalConfig = args[args.length - 1]
// Extract abort property from the config
let {abort, ...config} = originalConfig
// Create cancel token and abort method only if abort
// function was passed
if (typeof abort === 'function') {
const { cancel, token } = getCancelSource()
config.cancelToken = token
abort(cancel)
}
try {
// Spread all arguments from args besides the original config,
// and pass the rest of the config without abort property
return await fn(...args.slice(0, args.length - 1), config)
} catch (error) {
// Add "aborted" property to the error if the request was canceled
didAbort(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 ...