import { useCallback, useEffect, useState } from "react"; export type AsyncReturn = { loading: boolean; error?: Error | null; value?: T; }; export default function useAsync( callback: () => Promise, dependencies: unknown[] = [] ): AsyncReturn { const [loading, setLoading] = useState(true); const [error, setError] = useState(); const [value, setValue] = useState(); const callbackMemoized = useCallback(() => { setLoading(true); setError(undefined); setValue(undefined); callback() .then((result) => setValue(result)) .catch((err) => setError(err)) .finally(() => setLoading(false)); }, [...dependencies]); useEffect(() => { callbackMemoized(); }, [callbackMemoized]); return { loading, error, value }; }