import React from 'react'
import { useAuthUser } from '~/src/contexts/AuthUser'
import { useInterceptor } from './useInterceptor'
/**
* Setup axios interceptors to work with auth
*/
const AxiosProvider: React.FC = ({ children }) => {
const { token, logout } = useAuthUser()
useInterceptor((config) => {
if (token) {
config.headers['Authorization'] = `Bearer ${token}`
}
return config
})
useInterceptor(null, (err) => {
if (err.response.status === 401 && !err.config.url.includes('/oauth/token')) {
logout()
}
return Promise.reject(err)
})
return <>{children}</>
}
export { AxiosProvider }
Last active
May 13, 2022 02:18
-
-
Save srph/e5fdc022cf893bcc8df840ab5caf244f to your computer and use it in GitHub Desktop.
React: axios useInterceptor hook
This file contains hidden or 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 { useEffect } from 'react' | |
import { useLatestValue } from '~/src/hooks' | |
import { AxiosRequestConfig, AxiosError } from 'axios' | |
import { axios } from './axios' | |
type RequestInterceptor = (config: AxiosRequestConfig) => AxiosRequestConfig | |
type ResponseInterceptor = (error: AxiosError) => Promise<AxiosError> | |
const useInterceptor = (req?: RequestInterceptor, res?: ResponseInterceptor) => { | |
const reqRef = useLatestValue(req) | |
const resRef = useLatestValue(res) | |
useEffect(() => { | |
const requestEject = axios.interceptors.request.use((config: AxiosRequestConfig) => { | |
return reqRef.current ? reqRef.current(config) : config | |
}) | |
const responseEject = axios.interceptors.response.use(null, (error: AxiosError) => { | |
return resRef.current ? resRef.current.(error) : Promise.reject(error) | |
}) | |
return () => { | |
axios.interceptors.request.eject(requestEject) | |
axios.interceptors.response.eject(responseEject) | |
} | |
}, []) | |
} | |
export { useInterceptor } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment