21 lines
646 B
JavaScript
21 lines
646 B
JavaScript
import { useEffect, useState } from 'react'
|
|
|
|
// Minimal data-fetching hook: runs `fn` on mount / when deps change.
|
|
export function useAsync(fn, deps = []) {
|
|
const [state, setState] = useState({ loading: true, error: null, data: null })
|
|
|
|
useEffect(() => {
|
|
let active = true
|
|
setState({ loading: true, error: null, data: null })
|
|
fn()
|
|
.then((data) => active && setState({ loading: false, error: null, data }))
|
|
.catch((error) => active && setState({ loading: false, error, data: null }))
|
|
return () => {
|
|
active = false
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, deps)
|
|
|
|
return state
|
|
}
|