Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect, useState } from "react/cjs/react.development"
- export const useData=(url, method = "GET")=>{
- const [isPending,setIsPending] = useState(null)
- const [data,setData]=useState(null)
- const [error,setError]=useState(null)
- const [options,setOptions]= useState(null)
- const postData=(postData)=>{
- setOptions({
- method:"POST",
- headers:{
- "Content-Type":"application/json"
- },
- body: JSON.stringify(postData)
- })
- }
- useEffect(()=>{
- const controller = new AbortController()
- const fetchData = async (fetchOptions)=>{
- setIsPending(true)
- try{
- const res = await fetch(url,{...fetchOptions,signal:controller.signal})
- if(res.ok){
- const resData = await res.json()
- setIsPending(false)
- setData(resData)
- setError(null)
- }else{
- throw new Error("request wasn't match ")
- }
- }catch(err){
- if(err.name === "AbortError"){
- console.log("Request was aborted")
- }else{
- setError(err)
- setIsPending(false)
- }
- }
- }
- if(method==="GET"){
- fetchData()
- }
- if(method==="POST" && options){
- fetchData(options)
- }
- return()=>{
- controller.abort()
- }
- },[url,options,method])
- return{data,isPending,error,postData}
- }
Advertisement
Add Comment
Please, Sign In to add comment