Skip to content

Instantly share code, notes, and snippets.

@pikax
Created June 25, 2020 09:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pikax/b13fc50e46668659e9d2dd3851e83d9f to your computer and use it in GitHub Desktop.
Save pikax/b13fc50e46668659e9d2dd3851e83d9f to your computer and use it in GitHub Desktop.
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