w-aura/src/api/useApiCall.ts
2023-06-17 14:53:03 +03:00

25 lines
637 B
TypeScript

import { useState, useEffect } from "react";
interface HookResult<T> {
isPending: boolean
error: Error | null
data: T | null
}
type ApiMethod<T> = () => Promise<T>
export function useApiCall<T>(apiMethod: ApiMethod<T>): HookResult<T> {
const [data, setData] = useState<T | null>(null)
const [error, setError] = useState<Error | null>(null)
const [isPending, setIsPending] = useState<boolean>(true)
useEffect(() => {
apiMethod()
.then((data: T) => setData(data))
.catch((error: Error) => setError(error))
.finally(() => setIsPending(false))
}, [apiMethod])
return { isPending, error, data }
}