Skip to content

Instantly share code, notes, and snippets.

@foyez
Created October 12, 2021 02:34
Show Gist options
  • Select an option

  • Save foyez/ca969c13eab1203da20cad1967b08bd6 to your computer and use it in GitHub Desktop.

Select an option

Save foyez/ca969c13eab1203da20cad1967b08bd6 to your computer and use it in GitHub Desktop.
Cancel a api reqest using fetch and axios in React
import React, {useState, useEffect} from 'react'
const Example = () => {
const [user, setUser] = useState(null)
const signal = axios.CancelToken.source()
useEffect(() => {
(async function loadUser(){
try {
const {data} = await axios.get('https://randomuser.me/api', {
cancelToken: signal.token
})
setUser(data)
} catch (err) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
}
})()
return () => signal.cancel('API request is being cancelled')
}, [])
return (
<div>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
)
}
import React, {useState, useEffect} from 'react'
const Example = () => {
const [user, setUser] = useState(null)
const { signal, abort } = new AbortController()
useEffect(() => {
(async function loadUser(){
try {
const res = await fetch('https://randomuser.me/api', {
method: 'get',
signal
})
const data = await res.json()
setUser(data)
} catch (err) {
// handle error
}
})()
return () => abort()
}, [])
return (
<div>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment