Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react fetch custom hook

import { useEffect, useState } from "react"
import axios from "axios"


export default function useFetch(url){

    const [data,setData] = useState(null)
    const [error,setError] = useState(null)
    const [loading,setLoading] = useState(false)

    useEffect(() => {
        (
            async function(){
                try{
                    setLoading(true)
                    const response = await axios.get(url)
                    setData(response.data)
                }catch(err){
                    setError(err)
                }finally{
                    setLoading(false)
                }
            }
        )()
    }, [url])

    return { data, error, loading }

}
Comment

custom fetch hook-react.js

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 fetchData = async () => {
      setIsPending(true)
      
      try {
        const res = await fetch(url, { signal: controller.signal })
        if(!res.ok) {
          throw new Error(res.statusText)
        }
        const data = await res.json()

        setIsPending(false)
        setData(data)
        setError(null)
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("the fetch was aborted")
        } else {
          setIsPending(false)
          setError('Could not fetch the data')
        }
      }
    }

    fetchData()

    return () => {
      controller.abort()
    }

  }, [url])

  return { data, isPending, error }
}
Comment

custom fetch hook for react.js GET and POST request

import { useState, useEffect } from "react"

export const useFetch = (url, method = "GET") => {
  const [data, setData] = useState(null)
  const [isPending, setIsPending] = useState(false)
  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) {
          throw new Error(res.statusText)
        }
        const data = await res.json()

        setIsPending(false)
        setData(data)
        setError(null)
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("the fetch was aborted")
        } else {
          setIsPending(false)
          setError('Could not fetch the data')
        }
      }
    }

    // invoke the function
    if (method === "GET") {
      fetchData()
    }
    if (method === "POST" && options) {
      fetchData(options)
    }

    return () => {
      controller.abort()
    }

  }, [url, method, options])

  return { data, isPending, error, postData }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: java gson string to json 
Javascript :: Min-Stack Optimized Solution Via JS 
Javascript :: npm adm-zip 
Javascript :: scrapy javascript 
Javascript :: javascript sort array of objects by property alphabetically 
Javascript :: how to read all files in a folder in node js 
Javascript :: react how to update state array 
Javascript :: laravel react 
Javascript :: javascript date to firebase timestamp 
Javascript :: javascript check image src 
Javascript :: table sort datatable 
Javascript :: regular expressions password contains number 
Javascript :: javascript interval fixed number of times 
Javascript :: settimeout in javascript 
Javascript :: pyspark from_json example 
Javascript :: use eslint in vscode 
Javascript :: how to get class name in jquery 
Javascript :: Razorpay generate Signature in the node js 
Javascript :: [PrivateRoute] is not a <Route component. All component children of <Routes must be a <Route or <React.Fragment 
Javascript :: not getting any response with fetch javascript method 
Javascript :: change color js 
Javascript :: onclick change image javascript example 
Javascript :: javascript intl.numberformat reais 
Javascript :: como actualizar nodejs 
Javascript :: jquery attr 
Javascript :: unity javascript 
Javascript :: get first word in javascript 
Javascript :: get Two digit number js 
Javascript :: how to add custom font to react project 
Javascript :: jquery change page on click 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =