javascriptreactjsabort

How to check if a caught exception was thrown because of triggering an AbortController?


I created a Simple Blog site using React With TypeScript and made a custom hook (useFetch). This hook fetches data Inside the useEffect hook.

Here is the code:

const useFetch  = (url : string) => {
    interface Blogs{
        title:string,
        body:string,
        author?:string,
        id:number;
    }
    const [data , setData] = useState<Blogs[] | null>(null) 
    const [isPending , setIsPending] = useState<boolean>(true)
    const [error , setIsError] = useState(null)
    useEffect(()=>{  
        const controller = new AbortController();
        // const signal = controller.signal;

       setTimeout(() => {
            fetch(url , {signal:controller.signal})
            .then(res=> res.json())
            .then(data=> {
                setData(data)
                setIsPending(false)
            }).catch(err=>{
                if(err.message === "AbortError"){
                    console.log("Fetch Aborted");
                }else{
                    setIsError(err.message)
                    setIsPending(false)
                }
            })    
       }, 1000);
        return ()=>controller.abort();
    } , [url])

    return { data , isPending , error}
}

I added a setTimeout to check whether the abort controller is working or not.

The fetch brings data then it's catch .. with this message: signal is aborted without reason

Original the content.tsx code :

function Content(){

    const {data : blogs , isPending , error} = useFetch("http://localhost:800/blogs");
    let [name , setName]  = useState("Eshada");

    function handleClick():void {
        name = "Essam"
        setName("Essam")
        console.log(`Hello mr ${name} it's nice to meet you !!`);
    }

    return(
        <div className="content">
            <div className="container">
                <div className="articles-container">
                    {isPending && <div> Loading...</div>}
                    {error && <div> Some Thing went wrong : {error} </div>}
                    {blogs && <BlogList  name ="All Blogs" blogs = {blogs}/>} 
                </div>
                <button onClick={handleClick}>Click Me!</button>

            </div>
        </div>
    )
}

enter image description here


Solution

  • I figured it out. I just changed my catch code to be:

    .catch((err) => {
      if (err.name === 'AbortError') {
         console.log('Fetch aborted');
      } else {
         setError(err.message);
         setIsPending(false);
      }
    });
    

    In the line where I was originally checking err.message, I changed it to err.name and it worked!