Last active
February 23, 2021 07:43
-
-
Save zaingz/83ba5d8c4c7107f6fe1b273098bf7694 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, { CancelToken } from 'axios' | |
export default function useFetch (options) { | |
const [data, setData] = useState(null) | |
const [isLoading, setIsLoading] = useState(false) | |
const [error, setError] = useState(null) | |
useEffect(_ => { | |
const source = CancelToken.source(); | |
(async _ => { | |
setIsLoading(true) | |
try { | |
const response = await axios({ ...options, ...{ cancelToken: source.token } }) | |
setData(response) | |
setIsLoading(false) | |
} catch (e) { | |
if (axios.isCancel(e)) { | |
return | |
} | |
setIsLoading(false) | |
setError(e) | |
setData(null) | |
} | |
})() | |
return _ => source.cancel('useFetch cancelled') | |
}, [options.url, options.method]) | |
return { data, isLoading, error } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment