Skip to content

Instantly share code, notes, and snippets.

@dclstn
Created December 19, 2022 04:43
Show Gist options
  • Select an option

  • Save dclstn/4a22b84bfb7d4ff5e1e57b1dd5f26690 to your computer and use it in GitHub Desktop.

Select an option

Save dclstn/4a22b84bfb7d4ff5e1e57b1dd5f26690 to your computer and use it in GitHub Desktop.
useApi React Hook
import React from "react";
interface Response<T> {
data: T | null;
isFetching: boolean;
error: string | null;
isSuccess: boolean;
}
export function useApi<T>(apiFunction: () => Promise<any>): [Response<T>, () => void] {
const [response, setResponse] = React.useState<Response<T>>({
data: null,
isFetching: false,
error: null,
isSuccess: false,
});
const callback = React.useCallback(async () => {
setResponse({
data: null,
isFetching: true,
error: null,
isSuccess: false,
});
try {
const res = await apiFunction();
setResponse({...response, data: res, isFetching: false, isSuccess: true});
} catch (err) {
setResponse({...response, isFetching: false, error: (err as Error).message});
}
}, [apiFunction]);
return [response, callback];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment