| import { useEffect, useState } from 'react'; | |
| export function useAsync<T>(factory: () => Promise<T>, deps: unknown[]) { | |
| const [data, setData] = useState<T | null>(null); | |
| const [loading, setLoading] = useState(true); | |
| const [error, setError] = useState<string | null>(null); | |
| useEffect(() => { | |
| let active = true; | |
| setLoading(true); | |
| setError(null); | |
| factory() | |
| .then((result) => { | |
| if (active) { | |
| setData(result); | |
| } | |
| }) | |
| .catch((caught: Error) => { | |
| if (active) { | |
| setError(caught.message); | |
| } | |
| }) | |
| .finally(() => { | |
| if (active) { | |
| setLoading(false); | |
| } | |
| }); | |
| return () => { | |
| active = false; | |
| }; | |
| }, deps); | |
| return { data, loading, error }; | |
| } | |