Skip to content

Instantly share code, notes, and snippets.

@garthtee
Last active December 23, 2022 19:42
Show Gist options
  • Save garthtee/27dde226ecbc1c1bc384ffe7e8466169 to your computer and use it in GitHub Desktop.
Save garthtee/27dde226ecbc1c1bc384ffe7e8466169 to your computer and use it in GitHub Desktop.
An example of an Axios request that can be cancelled.
import React, {
Component,
useEffect
} from 'react';
import axios from 'axios';
const CancelToken = axios.CancelToken;
let cancel;
const AxiosCancelRequestExample = () => {
const makeRequest = () => {
if (cancel !== undefined) {
cancel();
}
axios.post(
'https://example.com', // Endpoint URL
requestBody, // E.g. {search: 'Jim Bob'},
{
cancelToken: new CancelToken((c) => {
cancel = c;
})
})
.then((response) => {
// Do your thing with the response
console.log(respone);
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log('Request cancelled successfully.');
return;
}
console.log('An error occurred.', error);
}
);
};
return (
<div>
<p>On each second click, you should see the request cancel.</p>
<button onClick={makeRequest}>
Click to make a request.
</button>
</div>
);
};
export default AxiosCancelRequestExample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment