Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Cancel API requests

You may cancel any request made through API category by keeping a reference to the promise returned.

const promise = API.get(myApiName, myPath, myInit);
try {
await promise;
} catch (error) {
console.log(error);
// If the error is because the request was cancelled you can confirm here.
if(API.isCancel(error)) {
// "my message for cancellation"
console.log(error.message);
// handle user cancellation logic
}
}
...
// To cancel the above request
API.cancel(promise, "my message for cancellation");

You need to ensure that the promise returned from API.get() or any other API calls has not been modified. Typically async functions wrap the promise being returned into another promise. For example, the following will not work

async function makeAPICall() {
return API.get(myApiName, myPath, myInit);
}
const promise = makeAPICall();
// The following will NOT cancel the request.
API.cancel(promise, 'my error message');