1
- import React , { createContext , useCallback , useContext , useEffect , useState } from 'react'
1
+ import React , { createContext , MutableRefObject , useCallback , useContext , useEffect , useRef , useState } from 'react'
2
2
3
3
const MILLISECONDS_UNTIL_EXPIRY_CHECK = 10 * 1000 // check expiry every 10 seconds
4
4
const REMAINING_TOKEN_EXPIRY_TIME_ALLOWED = 60 * 1000 // 1 minute before token should be refreshed
@@ -49,9 +49,7 @@ interface AuthContext {
49
49
session : Session | undefined
50
50
setAccessToken : ( accessToken : string | undefined ) => void
51
51
setSession : ( session : Session | undefined ) => void
52
-
53
- isCheckingAuth : boolean
54
- setCheckingAuth : ( checking : boolean ) => void
52
+ isCheckingAuth : MutableRefObject < boolean >
55
53
}
56
54
57
55
interface AuthWrapperProps {
@@ -63,7 +61,7 @@ const Context = createContext<AuthContext>(undefined as any)
63
61
export const AuthProvider = ( props : AuthWrapperProps ) => {
64
62
const [ accessToken , setAccessToken ] = useState < string | undefined > ( )
65
63
const [ session , setSession ] = useState < Session | undefined > ( )
66
- const [ isCheckingAuth , setCheckingAuth ] = useState < boolean > ( false )
64
+ const isCheckingAuth = useRef < boolean > ( false )
67
65
68
66
return (
69
67
< Context . Provider
@@ -73,7 +71,6 @@ export const AuthProvider = (props: AuthWrapperProps) => {
73
71
setAccessToken,
74
72
setSession,
75
73
isCheckingAuth,
76
- setCheckingAuth,
77
74
} }
78
75
>
79
76
{ props . children }
@@ -140,9 +137,13 @@ export const useAuth = () => {
140
137
141
138
export const useAuthCheck = ( ) => {
142
139
const context = useContext ( Context )
140
+ const { isCheckingAuth } = context
143
141
144
142
const refreshIfNecessary = useCallback ( async ( ) => {
145
- context . setCheckingAuth ( true )
143
+ if ( isCheckingAuth . current ) {
144
+ return
145
+ }
146
+ isCheckingAuth . current = true
146
147
147
148
const isExpiringSoon = ( ) => {
148
149
if ( context . session ?. expiresOnUTC ) {
@@ -183,7 +184,7 @@ export const useAuthCheck = () => {
183
184
// console.log(`${context.accessToken ? 'access token' : ''} ${isExpiringSoon() ? ' is not expiring' : ''}`)
184
185
}
185
186
186
- context . setCheckingAuth ( false )
187
+ isCheckingAuth . current = false
187
188
} , [ context . accessToken , context . session ] )
188
189
189
190
useEffect ( ( ) => {
0 commit comments