reactjsfetchrequest-cancelling

Unhandled Rejection (AbortError): The operation was aborted


EDIT: react app crash only in firefox. when im using chrome, react app not crash. How to handle crash in firefox?

I want to cancel http request when component is unmounted. Im using fetch() and AbortController.

Im following this guide.

But when component unmounted, react app is crash.

enter image description here

this is my code:

import React, { useEffect, useState } from 'react'
import AbortController from "abort-controller"

function Label(){
  const abortController = new AbortController()
  const signal = abortController.signal
  const [labels, setLabels] = useState([])

    useEffect(() => {
      async function getLabels(){
          const req = await fetch(`${process.env.REACT_APP_SERVER_URL}/label`, {
              credentials: 'include',
              signal: signal
          })
          const res = await req.json()
        
          setLabels(res.data)
      }
    
      getLabels()
    
      // cancel httprequest if component unmounted
      return function cancel(){
          abortController.abort()
      }
  }, [])


return (<p>ehehe</p>)

}

Solution

  • From MSDN:

    Note: When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.

    So you are getting the exception because infact you call abort on fetch. I would suggest to modify your useEffect in this way:

    useEffect(() => {
          async function getLabels(){
              try {
                 const req = await fetch(`${process.env.REACT_APP_SERVER_URL}/label`, {
                  credentials: 'include',
                  signal: signal
                 })
                 const res = await req.json()
            
                 setLabels(res.data)
              }
              catch(error) {
                 if (error.name === "AbortError") return;
                 console.log("Error ", error);
              }
          }
        
          getLabels()
        
          // cancel httprequest if component unmounted
          return function cancel(){
              abortController.abort()
          }
      }, [])