Skip to content

Instantly share code, notes, and snippets.

@vitorfranca
Created June 17, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitorfranca/699ba705cf6c176d1091a0040d1b6ec3 to your computer and use it in GitHub Desktop.
Save vitorfranca/699ba705cf6c176d1091a0040d1b6ec3 to your computer and use it in GitHub Desktop.
React Hook - useFetch with loading, error and refetch function
import { useState, useEffect } from 'react'
export const useFetch = (url) => {
const [data, setData] = useState(null)
const [isLoading, setIsLoading] = useState(false)
const [hasError, setHasError] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [refetchIndex, setRefetchIndex] = useState(0)
const refetch = () => setRefetchIndex((prevRefetchIndex) => prevRefetchIndex + 1)
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
try {
const response = await fetch(url)
const result = await response.json()
if(response.ok) {
setData(result)
} else {
setHasError(true)
setErrorMessage(result)
}
} catch (error) {
setHasError(true)
setErrorMessage(error.message)
} finally {
setIsLoading(false)
}
}
fetchData()
}, [url, refetchIndex])
return { data, isLoading, hasError, errorMessage, refetch }
}
export default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment