Skip to content

Instantly share code, notes, and snippets.

@Alonso-Pablo
Created March 12, 2022 21:49
Show Gist options
  • Save Alonso-Pablo/afbf461c5d65d5f545e2328318d6ccae to your computer and use it in GitHub Desktop.
Save Alonso-Pablo/afbf461c5d65d5f545e2328318d6ccae to your computer and use it in GitHub Desktop.
Avoids errors if the request cannot be resolved because the React component was disassembled.
import { useEffect } from 'react'
import { AxiosResponse } from 'axios'
export const useAsync = (
asyncFn: () => Promise<AxiosResponse<any, any>>,
successFunction: Function,
returnFunction: Function,
dependencies: any[] = []
) => {
useEffect(() => {
let isActive = true
asyncFn().then(({ data }) => {
if (isActive) successFunction(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