Skip to content

Instantly share code, notes, and snippets.

@CarlosRA97
Last active May 4, 2022 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarlosRA97/2cb14d12cff7cc19f5522e718505a0dc to your computer and use it in GitHub Desktop.
Save CarlosRA97/2cb14d12cff7cc19f5522e718505a0dc to your computer and use it in GitHub Desktop.
Async hook for Axios in ReactJS
import { AxiosResponse } from 'axios';
import { useEffect } from 'react';
export const useAsync = (
asyncFn: () => Promise<AxiosResponse<any, any>>,
successFunction: Function,
returnFunction: Function,
dependencies: any[] = []
) => {
useEffect(() => {
let isActive = true;
asyncFn().then((result) => {
if (isActive) successFunction(result.data);
});
return () => {
returnFunction && returnFunction();
isActive = false;
};
}, dependencies);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment