Usage
As a hook
import { useAsync } from "react-async"
// You can use async/await or any function that returns a Promise
const loadPlayer = async ({ playerId }, { signal }) => {
const res = await fetch(`/api/players/${playerId}`, { signal })
if (!res.ok) throw new Error(res.statusText)
return res.json()
}
const MyComponent = () => {
const { data, error, isPending } = useAsync({ promiseFn: loadPlayer, playerId: 1 })
if (isPending) return "Loading..."
if (error) return `Something went wrong: ${error.message}`
if (data)
return (
<div>
<strong>Player data:</strong>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
return null
}With useFetch
useFetchAs a component
As a factory
With helper components
As compounds to <Async>
<Async>Last updated
Was this helpful?