Skip to content

Instantly share code, notes, and snippets.

@zaingz
Last active February 23, 2021 07:43
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 zaingz/83ba5d8c4c7107f6fe1b273098bf7694 to your computer and use it in GitHub Desktop.
Save zaingz/83ba5d8c4c7107f6fe1b273098bf7694 to your computer and use it in GitHub Desktop.
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