Last active
December 23, 2022 19:42
-
-
Save garthtee/27dde226ecbc1c1bc384ffe7e8466169 to your computer and use it in GitHub Desktop.
An example of an Axios request that can be cancelled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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