11import {
22 type ReactNode ,
33 useCallback ,
4+ useEffect ,
45 useMemo ,
56 useRef ,
67 useState
@@ -44,16 +45,6 @@ function clientFromCredential({ host, accessToken }: StoredCredential): Client {
4445 return createClient ( { baseURL : host , auth : ( ) => accessToken } )
4546}
4647
47- function addUnauthorizedInterceptor ( client : Client , onUnauthorized : ( ) => void ) {
48- client . instance . interceptors . response . use ( undefined , ( error ) => {
49- if ( error ?. response ?. status === 401 ) {
50- sessionStorage . setItem ( 'logout_reason' , 'session_expired' )
51- onUnauthorized ( )
52- }
53- return Promise . reject ( error )
54- } )
55- }
56-
5748const EMPTY_STATE : AuthState = {
5849 host : '' ,
5950 username : '' ,
@@ -62,22 +53,36 @@ const EMPTY_STATE: AuthState = {
6253}
6354
6455export function AuthProvider ( { children } : { children : ReactNode } ) {
65- const logoutRef = useRef < ( ( ) => void ) | null > ( null )
66-
6756 const [ state , setState ] = useState < AuthState > ( ( ) => {
6857 const stored = loadCredential ( )
6958 if ( ! stored ) return EMPTY_STATE
70- const client = clientFromCredential ( stored )
71- addUnauthorizedInterceptor ( client , ( ) => logoutRef . current ?.( ) )
72- return { ...stored , client }
59+ return { ...stored , client : clientFromCredential ( stored ) }
7360 } )
7461
7562 const logout = useCallback ( ( ) => {
7663 window . localStorage . removeItem ( LOCAL_STORAGE_KEY )
7764 setState ( EMPTY_STATE )
7865 } , [ ] )
7966
80- logoutRef . current = logout
67+ const logoutRef = useRef ( logout )
68+ useEffect ( ( ) => {
69+ logoutRef . current = logout
70+ } , [ logout ] )
71+
72+ useEffect ( ( ) => {
73+ const client = state . client
74+ if ( ! client ) return
75+ const id = client . instance . interceptors . response . use ( undefined , ( error ) => {
76+ if ( error ?. response ?. status === 401 ) {
77+ sessionStorage . setItem ( 'logout_reason' , 'session_expired' )
78+ logoutRef . current ( )
79+ }
80+ return Promise . reject ( error )
81+ } )
82+ return ( ) => {
83+ client . instance . interceptors . response . eject ( id )
84+ }
85+ } , [ state . client ] )
8186
8287 const login = useCallback (
8388 async ( host : string , username : string , password : string ) => {
@@ -93,7 +98,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
9398 }
9499 const accessToken = data . access_token
95100 client . setConfig ( { baseURL : host , auth : ( ) => accessToken } )
96- addUnauthorizedInterceptor ( client , ( ) => logoutRef . current ?.( ) )
97101
98102 window . localStorage . setItem (
99103 LOCAL_STORAGE_KEY ,
0 commit comments