Created
January 2, 2020 06:27
-
-
Save itashdv/18c393eb70c047e8ae9b16de6fe1d8cb to your computer and use it in GitHub Desktop.
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 axios, {AxiosResponse} from "axios"; | |
const useAxiosFetch = (url: string, timeout?: number) => { | |
const [data, setData] = useState<AxiosResponse | null>(null); | |
const [error, setError] = useState(false); | |
const [errorMessage, setErrorMessage] = useState(null); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
let unmounted = false; | |
let source = axios.CancelToken.source(); | |
axios.get(url, { | |
cancelToken: source.token, | |
timeout: timeout | |
}) | |
.then(a => { | |
if (!unmounted) { | |
// @ts-ignore | |
setData(a.data); | |
setLoading(false); | |
} | |
}).catch(function (e) { | |
if (!unmounted) { | |
setError(true); | |
setErrorMessage(e.message); | |
setLoading(false); | |
if (axios.isCancel(e)) { | |
console.log(`request cancelled:${e.message}`); | |
} else { | |
console.log("another error happened:" + e.message); | |
} | |
} | |
}); | |
return function () { | |
unmounted = true; | |
source.cancel("Cancelling in cleanup"); | |
}; | |
}, []); | |
return {data, loading, error, errorMessage}; | |
}; | |
export default useAxiosFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment