Search⌘ K
AI Features

Abort Property

Explore how to implement the abort property in Vue's API layer to cleanly cancel asynchronous requests. Learn to modify API functions for better request control, prevent unnecessary server load, and improve user experience by managing rapid input scenarios effectively.

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.

Javascript (babel-node)
// 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. It injects the cancelToken into the config object. The main difference lies in how we get access to the abort method. At this point, we know for sure that a config object exists due to default parameters specified when the ...