Skip to content

Commit 8d96221

Browse files
gx0rWulf
authored andcommitted
Use ref for isCheckingAuth to prevent excess check calls
1 parent bd256ac commit 8d96221

File tree

1 file changed

+9
-8
lines changed
  • create-rust-app_cli/template-plugin-auth/frontend/src/hooks

1 file changed

+9
-8
lines changed

create-rust-app_cli/template-plugin-auth/frontend/src/hooks/useAuth.tsx

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'
1+
import React, { createContext, MutableRefObject, useCallback, useContext, useEffect, useRef, useState } from 'react'
22

33
const MILLISECONDS_UNTIL_EXPIRY_CHECK = 10 * 1000 // check expiry every 10 seconds
44
const REMAINING_TOKEN_EXPIRY_TIME_ALLOWED = 60 * 1000 // 1 minute before token should be refreshed
@@ -49,9 +49,7 @@ interface AuthContext {
4949
session: Session | undefined
5050
setAccessToken: (accessToken: string | undefined) => void
5151
setSession: (session: Session | undefined) => void
52-
53-
isCheckingAuth: boolean
54-
setCheckingAuth: (checking: boolean) => void
52+
isCheckingAuth: MutableRefObject<boolean>
5553
}
5654

5755
interface AuthWrapperProps {
@@ -63,7 +61,7 @@ const Context = createContext<AuthContext>(undefined as any)
6361
export const AuthProvider = (props: AuthWrapperProps) => {
6462
const [accessToken, setAccessToken] = useState<string | undefined>()
6563
const [session, setSession] = useState<Session | undefined>()
66-
const [isCheckingAuth, setCheckingAuth] = useState<boolean>(false)
64+
const isCheckingAuth = useRef<boolean>(false)
6765

6866
return (
6967
<Context.Provider
@@ -73,7 +71,6 @@ export const AuthProvider = (props: AuthWrapperProps) => {
7371
setAccessToken,
7472
setSession,
7573
isCheckingAuth,
76-
setCheckingAuth,
7774
}}
7875
>
7976
{props.children}
@@ -140,9 +137,13 @@ export const useAuth = () => {
140137

141138
export const useAuthCheck = () => {
142139
const context = useContext(Context)
140+
const { isCheckingAuth } = context
143141

144142
const refreshIfNecessary = useCallback(async () => {
145-
context.setCheckingAuth(true)
143+
if (isCheckingAuth.current) {
144+
return
145+
}
146+
isCheckingAuth.current = true
146147

147148
const isExpiringSoon = () => {
148149
if (context.session?.expiresOnUTC) {
@@ -183,7 +184,7 @@ export const useAuthCheck = () => {
183184
// console.log(`${context.accessToken ? 'access token' : ''} ${isExpiringSoon() ? ' is not expiring' : ''}`)
184185
}
185186

186-
context.setCheckingAuth(false)
187+
isCheckingAuth.current = false
187188
}, [context.accessToken, context.session])
188189

189190
useEffect(() => {

0 commit comments

Comments
 (0)