Skip to content

Instantly share code, notes, and snippets.

@lucax88x
Created February 13, 2020 09:31
Show Gist options
  • Save lucax88x/e4a9c064e211c48578e281736618bf39 to your computer and use it in GitHub Desktop.
Save lucax88x/e4a9c064e211c48578e281736618bf39 to your computer and use it in GitHub Desktop.
import { useCallback, useState } from 'react';
export interface ApiResult<R> {
data: R | null;
isBusy: boolean;
isError: boolean;
isSuccess: boolean;
}
function useCall<D, R>(
fn: (data?: D) => Promise<R>,
): [ApiResult<R>, (data?: D) => Promise<void>] {
const [result, setResult] = useState<ApiResult<R>>({
data: null,
isBusy: false,
isError: false,
isSuccess: false,
});
const asyncFn = useCallback(
async (data?: D) => {
setResult({
data: null,
isBusy: true,
isError: false,
isSuccess: false,
});
try {
const res = await fn(data);
setResult({
data: res,
isBusy: false,
isError: false,
isSuccess: true,
});
} catch (error) {
console.error(error);
setResult({
data: null,
isBusy: false,
isError: true,
isSuccess: false,
});
}
},
[fn],
);
return [result, asyncFn];
}
export function useGet<R>(functionName: string) {
return useCall(() => get<R>(functionName));
}
export function usePost<D, R>(functionName: string) {
return useCall((data?: D) => {
if (!data) return Promise.reject('No data');
return post<D, R>(functionName, data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment