aytdev

useFetch

Dec 22nd, 2021
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect } from "react";
  2. export const useFetch=(url)=>{
  3.     const [data,setData] = useState(null)
  4.     const [isPending,setIsPending]=useState(false)
  5.     const [error,setError]=useState(null)
  6.     useEffect(()=>{
  7.         const controller = new AbortController()
  8.         const fatchData = async ()=>{
  9.            
  10.  
  11.             setIsPending(true)
  12.             try{
  13.                 const res = await fetch(url,{signal:controller.signal})
  14.                 if(!res.ok){
  15.                     throw new Error(res.statusText)
  16.                 }else{
  17.                     const json = await res.json();
  18.                     setIsPending(false)
  19.                     setData(json)
  20.                     setError(null)
  21.  
  22.                 }
  23.  
  24.  
  25.             }catch(err){
  26.                
  27.                 if(err.name==="AbortError"){
  28.                     console.log("the Fetch was abourted");
  29.                 }else{
  30.                     setIsPending(false)
  31.                     setError(err)
  32.                     console.error(err.message)
  33.                 }
  34.             }
  35.         }
  36.         fatchData()
  37.         return()=>{
  38.            controller.abort()
  39.         }
  40.     },[url])
  41.  
  42.     return {data,isPending,error}
  43. }
Advertisement
Add Comment
Please, Sign In to add comment