Created
June 25, 2020 09:12
-
-
Save pikax/b13fc50e46668659e9d2dd3851e83d9f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface UseApiResult< | |
T, | |
TExecuteFactory extends (...args: any) => Promise<T | undefined>, | |
TError = any | |
> { | |
result: Ref<T | null>; | |
isLoading: Ref<boolean>; | |
error: Ref<TError | null>; | |
execute: TExecuteFactory; | |
} | |
function useApi<TResult, TArgs extends any[]>( | |
factory: (...args: TArgs) => RequestInfo, | |
handleResponse: (response: Response) => Promise<TResult> | |
): UseApiResult<TResult, (...args: TArgs) => Promise<TResult | undefined>> { | |
const isLoading = ref(false); | |
const result = ref<TResult | null>(null) as Ref<TResult | null>; | |
const error = ref(null); | |
const execute = async (...args: TArgs) => { | |
const request = factory(...args); | |
isLoading.value = true; | |
error.value = null; | |
try { | |
const response = await fetch(request).then(handleResponse); | |
result.value = response; | |
return response; | |
} catch (e) { | |
error.value = e; | |
result.value = null; | |
} finally { | |
isLoading.value = false; | |
} | |
}; | |
return { | |
isLoading, | |
result, | |
error, | |
execute, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment