Skip to content

Instantly share code, notes, and snippets.

@DarlonHenrique
Created October 29, 2021 04:58
Show Gist options
  • Save DarlonHenrique/b593924f36a47a1c32d8ab94f5988bd3 to your computer and use it in GitHub Desktop.
Save DarlonHenrique/b593924f36a47a1c32d8ab94f5988bd3 to your computer and use it in GitHub Desktop.
a custom hook for make easy and util fetch's with loading and error state using react
import React from 'react'
const useFetch = () => {
const [data, setData] = React.useState(null)
const [error, setError] = React.useState(null)
const [loading, setLoading] = React.useState(null)
const request = React.useCallback(async (url, options) => {
let response
let json
try {
setError(null)
setLoading(true)
response = await fetch(url, options)
json = await response.json()
setData(json)
setLoading(true)
} catch (error) {
setError(error)
} finally {
setLoading(false)
return { response, json }
}
}, [])
return { request, data, loading, error }
}
export default useFetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment