Cancel window.fetch with AbortController
3/27/2019
I have longed for being able to cancel `window.fetch` requests in JavaScript. It is something particularly useful, especially to adhere to React's Lifecycle, and even more so with the introduction of React Hooks.
Thankfully, we have something called AbortController
!
const abortController = new AbortController()
const promise = window.fetch('https://api.example.com/v1/me', {
headers: { Authorization: `Bearer [my access token]` },
method: 'GET',
mode: 'cors',
signal: abortController.signal
})
.then(res => res.json())
.then(res => { console.log(res.me) })
.catch(err => { console.error('Request failed', err) }) // Cancel the request if it takes more than 5 seconds setTimeout(() => abortController.abort(), 5000)
...