Last active
September 10, 2020 03:43
-
-
Save bardiarastin/7bbefcc3da16b1d5b5be16f6ce2b10b0 to your computer and use it in GitHub Desktop.
simple React custom hook for api access
This file contains 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
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