react-use-async-loading
v1.0.2
Published
Made with create-react-library
Maintainers
Readme
react-use-async-loading
A React hook for managing async loading state
Install
npm install --save react-use-async-loadingUsage
import { useLoading } from 'react-use-async-loading'Show a spinner while fetching data
const Page = () => {
const { loading, run } = useLoading()
useEffect(() => {
run(() => fetch('/data.json').then(res => res.json()).then(setData))
}, [])
if (loading) return <Spinner />
return <div>Data was loaded</div>
}Disable a button while submitting
const Form = () => {
const { loading, run } = useLoading()
const onSubmit = (values) => {
run(() => axios.post('/register', values))
}
return <Form disabled={loading} onSubmit={onSubmit} />
}Handle error state
const Page = () => {
const { status, error, run } = useLoading()
useEffect(() => {
run(() => fetch('/data.json'))
}, [])
if (status === 'loading') return <Spinner />
if (status === 'error') return <Error message={error.message} />
if (status === 'success') return <div>Done</div>
return null
}Cancel previous request automatically
run() accepts a factory function that receives an AbortSignal. If run() is called again before the previous call resolves, the previous request is aborted automatically.
const Search = () => {
const { loading, run } = useLoading()
const onSearch = (query) => {
run((signal) => fetch(`/search?q=${query}`, { signal }))
}
return <SearchInput loading={loading} onChange={onSearch} />
}Reset state
const { status, run, reset } = useLoading()
// Aborts any in-flight request and resets status back to 'idle'
reset()API
const { status, loading, idle, error, run, reset } = useLoading(defaultLoading?)| Name | Type | Description |
|---|---|---|
| status | 'idle' \| 'loading' \| 'success' \| 'error' | Unified async state |
| loading | boolean | true while run() is pending |
| idle | boolean | true before run() has ever been called |
| error | unknown | Error from the last failed run(), otherwise null |
| run(fn) | (fn: (signal) => Promise) => Promise | Starts async operation. Aborts previous if still pending. Also accepts a plain promise. |
| reset() | () => void | Aborts in-flight request, resets all state to initial |
License
MIT © Max Ivaneychyk
