Skip to content

Instantly share code, notes, and snippets.

@bardiarastin
Last active September 10, 2020 03:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bardiarastin/7bbefcc3da16b1d5b5be16f6ce2b10b0 to your computer and use it in GitHub Desktop.
Save bardiarastin/7bbefcc3da16b1d5b5be16f6ce2b10b0 to your computer and use it in GitHub Desktop.
simple React custom hook for api access
import { useState, useEffect } from "react";
import { AxiosPromise } from "axios";
interface IState<T = any> {
isLoading: boolean;
isError: boolean;
data: T;
}
const initialState: IState = {
data: null,
isError: false,
isLoading: false,
};
type ApiType = (...params: any) => AxiosPromise;
const useApi = <U>(
api: ApiType,
params: any[] = [],
initial: IState = initialState,
onFetchData?: (data: U) => void,
silentError: boolean = false
): {
data: U | null;
isLoading: boolean;
isError: boolean;
fetchData: () => void;
} => {
const [state, setState] = useState<IState<U | null>>(initial);
const { data, isLoading, isError } = state;
const fetchData = async () => {
setState(prev => ({ ...prev, isError: false, isLoading: true }));
try {
const result = await api(...(params as Parameters<ApiType>));
setState({ isError: false, isLoading: false, data: result.data });
onFetchData && onFetchData(result.data);
} catch (error) {
setState(prev => ({ ...prev, isError: !silentError, isLoading: false }));
}
};
useEffect(() => {
if (isLoading) return;
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...params]);
return { data, isLoading, isError, fetchData };
};
export default useApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment