Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect } from "react";
- export const useFetch=(url)=>{
- const [data,setData] = useState(null)
- const [isPending,setIsPending]=useState(false)
- const [error,setError]=useState(null)
- useEffect(()=>{
- const controller = new AbortController()
- const fatchData = async ()=>{
- setIsPending(true)
- try{
- const res = await fetch(url,{signal:controller.signal})
- if(!res.ok){
- throw new Error(res.statusText)
- }else{
- const json = await res.json();
- setIsPending(false)
- setData(json)
- setError(null)
- }
- }catch(err){
- if(err.name==="AbortError"){
- console.log("the Fetch was abourted");
- }else{
- setIsPending(false)
- setError(err)
- console.error(err.message)
- }
- }
- }
- fatchData()
- return()=>{
- controller.abort()
- }
- },[url])
- return {data,isPending,error}
- }
Advertisement
Add Comment
Please, Sign In to add comment