React hook for conveniently use Fetch API. It will take url and the extra header if needed.
import useFetch from 'react-custom-fetch-hook'
function CustomHook() {
const {data,loading} = useFetch('https://quotable.io/quotes',{})
if(loading){
return <h3>Loading...</h3>
}
return (
<div>
{data.results.map((result) => (
<p key={result._id}>{result.content}</p>
))}
</div>
)
}
useFetch accepts the same arguments as fetch function.
Install it with npm:
npm i react-custom-fetch-hook --save
The useFetch
hook returns an error
field at any fetch exception.
The error
field extends Error
and has status
and statusText
fields equal to Response.
function CustomHook() {
const {data,loading ,error } = useFetch("https://quotable.io/quotes");
if (error) {
return <div>
<p>Code: ${error.status}</p>
<p>Message: ${error.statusText}</p>
</div>
}
};