Created
June 17, 2020 17:53
-
-
Save vitorfranca/699ba705cf6c176d1091a0040d1b6ec3 to your computer and use it in GitHub Desktop.
React Hook - useFetch with loading, error and refetch function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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