How to use the AbortController Web API with fetch

How to use the AbortController Web API with fetch

The AbortController is an interface where you can create an instance and that instance is an object that can be used to abort requests.

This can be helpful if you have to abort the fetch requests conditionally, we can destructure the "signal" from the controller and pass it as options in the fetch request. So the signal kind of tracks the request and allows us to abort the request whenever and however we want. We can use controller.abort() to abort that request.

const controller = new AbortController()
const signal = controller.signal

const getData = async() => {
    try {
        const res = await fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
        const data = await res.json()
        console.log("data",data)
    }catch(err) {
        console.log("err", err)
    }

}

getData()
controller.abort()

AbortController with fetch in React

While fetching the data with the fetch in useEffect hook, it is important to clean up the requests once the component is unmounted. We can abort the network calls while cleaning up the useEffect. For example

useEffect(() => {
    const controller = new AbortController()
    const signal = controller.signal

    fetch(url, { signal }).then( async (res) => {
        if(res.ok){
            const data = await res.json()
            console.log(data)
        } else {
            console.log("error occurred")
        }
    }).catch((error) => {
        console.log(error)
    })

    return () => {
        controller.abort()
    }    
}, [])

That is it guys! Please do comment if there are any other ways to abort the network calls conditionally :)

#javascript #react