aytdev

useData

Dec 22nd, 2021
1,104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useEffect, useState } from "react/cjs/react.development"
  2.  
  3. export const useData=(url, method = "GET")=>{
  4.      const [isPending,setIsPending] = useState(null)
  5.      const [data,setData]=useState(null)
  6.      const [error,setError]=useState(null)
  7.      const [options,setOptions]= useState(null)
  8.      const postData=(postData)=>{
  9.         setOptions({
  10.             method:"POST",
  11.             headers:{
  12.                 "Content-Type":"application/json"
  13.             },
  14.             body: JSON.stringify(postData)
  15.         })
  16.      }
  17.      useEffect(()=>{
  18.         const controller = new AbortController()
  19.         const fetchData = async (fetchOptions)=>{
  20.             setIsPending(true)
  21.             try{
  22.                 const res = await fetch(url,{...fetchOptions,signal:controller.signal})
  23.                 if(res.ok){
  24.                     const resData = await res.json()
  25.                     setIsPending(false)
  26.                     setData(resData)
  27.                     setError(null)
  28.                 }else{
  29.                     throw new Error("request wasn't match ")
  30.                 }
  31.             }catch(err){
  32.                 if(err.name === "AbortError"){
  33.                     console.log("Request was aborted")
  34.  
  35.                 }else{
  36.                     setError(err)
  37.                     setIsPending(false)
  38.                 }
  39.             }
  40.         }
  41.         if(method==="GET"){
  42.            fetchData()
  43.         }
  44.         if(method==="POST" && options){
  45.           fetchData(options)
  46.          
  47.         }
  48.         return()=>{
  49.             controller.abort()
  50.         }
  51.      },[url,options,method])
  52.  
  53.  
  54.     return{data,isPending,error,postData}
  55. }
Advertisement
Add Comment
Please, Sign In to add comment