import { useState, useEffect } from 'react' import { ApiError } from './errors' interface HookResult { data: T | null error: ApiError | null isPending: boolean state: ApiCallState } type ApiMethod = () => Promise type ApiCallState = 'idle' | 'pending' | 'success' | 'error' export function useApiCall(apiMethod: ApiMethod): HookResult { const [data, setData] = useState(null) const [error, setError] = useState(null) const [state, setState] = useState('idle') const isPending = state === 'pending' useEffect(() => { setState('pending') apiMethod() .then((data: T) => { setData(data) setState('success') }) .catch((error: ApiError) => { setError(error) setState('error') }) }, [apiMethod]) return { isPending, error, data, state } }