@hmn/use-fetch
v0.2.6
Published
Fetch hook implementation with abort
Readme
@hmn/use-fetch
Fetch hook implementation with abort
Installation
npm install --save @hmn/use-fetchImporting the hook
import useFetch from '@hmn/use-fetch'Usage
const Demo = () => {
const { result = [] } = useFetch('https://api.punkapi.com/v2/beers/random')
const beer = result[0]
if (beer) {
const { name, image_url } = beer
return (
<article>
<h3>{name}</h3>
{image_url && (
<img
style={{ height: 200, margin: 20 }}
src={image_url}
alt={name}
/>
)}
</article>
)
}
return null
}Advanced usage
Pending state, error, run method (for refetching data)
const DemoAdvanced = () => {
const { pending, error, result = [], run } = useFetch('https://api.punkapi.com/v2/beers/random')
if (pending) {
return <progress />
}
if (error) {
return <div>Error: { error.message }</div>
}
const beer = result[0]
if (beer) {
const { name, abv, ibu, description, image_url } = beer
return (
<article>
<button onClick={run}>Refresh</button>
<h3>{name}</h3>
{image_url && (
<img
style={{ height: 200, margin: 20 }}
src={image_url}
alt={name}
/>
)}
<ul>
<li>ABV: {abv}</li>
<li>IBU: {ibu}</li>
</ul>
<p>{description}</p>
</article>
)
}
}
render(<Demo />)