Skip to content

Instantly share code, notes, and snippets.

@Pro542
Created November 25, 2019 09:40
Show Gist options
  • Save Pro542/81cd72778afca84361248466dc7bd54d to your computer and use it in GitHub Desktop.
Save Pro542/81cd72778afca84361248466dc7bd54d to your computer and use it in GitHub Desktop.
Reusable react state hook to handle api calls
/*
* Hook to reuse state logic for api calls
*
*/
function useApiCall(api: AxiosInstance, params: any[], onError: any => any) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(async () => {
setIsLoading(true)
try {
const response = await api(...params);
setData(response.data);
} catch(e) {
onError(e);
}
setIsLoading(false)
});
return [data, error, isLoading]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment