Skip to content

Instantly share code, notes, and snippets.

@jeferson-sb
Last active February 14, 2022 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeferson-sb/68e86e7ec6ac8af589d29de8e043a6e2 to your computer and use it in GitHub Desktop.
Save jeferson-sb/68e86e7ec6ac8af589d29de8e043a6e2 to your computer and use it in GitHub Desktop.
useAxios custom hook
import { useState, useCallback } from 'react'
import axios, { AxiosRequestConfig } from 'axios'
type HookOptions = {
baseURL?: string
beforeFetch?: (
value: AxiosRequestConfig<any>
) => AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>>
afterFetch?: (
value: AxiosRequestConfig<any>
) => AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>>
}
const useAxios = (options?: HookOptions) => {
const [results, setResults] = useState([])
const [headers, setHeaders] = useState({})
const [error, setError] = useState(null)
const [responseStatus, setResponseStatus] = useState(102)
const statusType = {
IDLE: 'IDLE',
FULFILLED: 'FULFILLED',
REJECTED: 'REJECTED',
}
const [status, setStatus] = useState(statusType.IDLE)
const instance = axios.create({
baseURL: options?.baseURL ?? process.env.API_URL,
})
const execute = useCallback(
async (url: string, requestOptions?: AxiosRequestConfig) => {
try {
const response = await instance({
method: 'get',
url,
...requestOptions,
})
if (response.status === 200 && response.data) {
setResults(response.data)
} else {
throw new Error(`request failed with status ${response.status}`)
}
setHeaders(response.headers)
setResponseStatus(response.status)
} catch (error) {
setError(error)
setStatus(statusType.REJECTED)
} finally {
setStatus(statusType.FULFILLED)
}
},
[instance, statusType.FULFILLED, statusType.REJECTED]
)
if (typeof options?.beforeFetch === 'function') {
instance.interceptors.request.use(options.beforeFetch)
}
if (typeof options?.afterFetch === 'function') {
instance.interceptors.response.use(options.afterFetch)
}
return {
execute,
results,
headers,
statusCode: responseStatus,
isLoading: status === statusType.IDLE,
isFinished: status === statusType.FULFILLED,
isRejected: status === statusType.REJECTED,
error,
}
}
export { useAxios }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment