Created
October 29, 2021 04:58
-
-
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
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 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