import { useEffect , useCallback } from 'react' ; import useAsync from './useAsync' ; import useApi from './useApi' ; export type QueryFunction = ( ... args : any [ ] ) => { method : string ; url : string ; } ; interface Result < R , U extends any [ ] > { result : R | undefined ; error : Error ; loading : boolean ; request : ( ... args : U ) => Promise < R > ; } const useApiResult = < R , F extends QueryFunction > ( fn , dependencies ? ) : Result < R , Parameters < F > > => { const request = useApi ( ) ; const { loading , result , error , run } = useAsync ( true ) ; const hookDependencies = dependencies || [ ] ; const requestAndSetResults = useCallback ( ( ... args ) => { const promise = request < R > ( fn ( ... args ) ) ; run ( promise ) ; return promise ; } , [ request , run , fn ] ) ; useEffect ( ( ) => { if ( dependencies ) { requestAndSetResults ( ... ( [ ] as unknown as Parameters < F > ) ) . catch ( ( ) => { } ) ; } } , [ ... hookDependencies ] ) ; if ( error ) { throw error ; } return { result , error , loading , request : requestAndSetResults , } ; } ; export default useApiResult ;