Last active
May 4, 2022 12:11
-
-
Save CarlosRA97/2cb14d12cff7cc19f5522e718505a0dc to your computer and use it in GitHub Desktop.
Async hook for Axios in ReactJS
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 { 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