Created
April 22, 2024 19:00
-
-
Save lovemycodesnippets/172dbc2cfe494f76abd3ea0eff1e179c to your computer and use it in GitHub Desktop.
AbortController API in React_3
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 axios from 'axios'; | |
import { useState, useRef } from 'react'; | |
function App() { | |
let controller = useRef('').current; | |
const [pictureUrl, setPictureUrl] = useState(''); | |
const getPicture = (e) => { | |
e.preventDefault(); | |
controller = new AbortController(); | |
axios | |
.get('https://randomuser.me/api/', { | |
signal: controller.signal, | |
}) | |
.then((res) => { | |
setPictureUrl(res.data.results[0].picture.large); | |
}) | |
.catch((err) => { | |
console.log(err); | |
}); | |
}; | |
const cancelRequest = (e) => { | |
e.preventDefault(); | |
controller.abort(); | |
}; | |
return ( | |
<div | |
style={{ | |
display: 'flex', | |
alignItems: 'center', | |
gap: '2rem', | |
flexDirection: 'column', | |
marginTop: '2rem', | |
}} | |
> | |
<div style={{ display: 'flex', gap: '2rem' }}> | |
<button onClick={getPicture}>Get Random Picture</button> | |
<button onClick={cancelRequest}> Cancel Request</button> | |
</div> | |
<div> | |
{pictureUrl !== '' ? <img src={pictureUrl} alt='random user' /> : null} | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment