Refactored AuthProvider and RefreshProvider to be simpler.

This commit is contained in:
Jesse Brault 2024-08-22 13:32:41 -05:00
parent a3376a8cc1
commit 5d1def13db
2 changed files with 8 additions and 40 deletions

View File

@ -1,4 +1,4 @@
import { createContext, PropsWithChildren, useContext, useReducer } from 'react'
import { createContext, PropsWithChildren, useContext, useState } from 'react'
import AccessToken from './types/AccessToken'
export interface AuthContextType {
@ -6,49 +6,17 @@ export interface AuthContextType {
putToken: (token: AccessToken | null) => void
}
interface AuthReducerState {
accessToken: AccessToken | null
}
const initialState: AuthReducerState = {
accessToken: null
}
type AuthReducerAction = PutTokenAction | ClearTokenAction
interface PutTokenAction {
tag: 'putToken'
accessToken: AccessToken
}
interface ClearTokenAction {
tag: 'clearToken'
}
const authReducer = (_state: AuthReducerState, action: AuthReducerAction): AuthReducerState => {
switch (action.tag) {
case 'putToken':
return { accessToken: action.accessToken }
case 'clearToken':
return { accessToken: null }
}
}
const AuthContext = createContext<AuthContextType | null>(null)
export const AuthProvider = ({ children }: PropsWithChildren) => {
const [state, dispatch] = useReducer(authReducer, initialState)
const [accessToken, setAccessToken] = useState<AccessToken | null>(null)
return (
<AuthContext.Provider
value={{
accessToken: state.accessToken,
accessToken,
putToken: token => {
if (token === null) {
dispatch({ tag: 'clearToken' })
} else {
dispatch({ tag: 'putToken', accessToken: token })
}
console.log(`token: ${token !== null ? token.token : null}`)
setAccessToken(token)
}
}}
>

View File

@ -1,5 +1,5 @@
import { useRouter } from '@tanstack/react-router'
import { createContext, useContext, PropsWithChildren, useRef, useCallback } from 'react'
import { createContext, PropsWithChildren, useCallback, useContext, useRef } from 'react'
import { ApiError } from './api/ApiError'
import refresh, { RefreshTokenError } from './api/refresh'
import { useAuth } from './AuthProvider'
@ -25,7 +25,6 @@ const RefreshProvider = ({ children }: PropsWithChildren) => {
const refreshing = useRef(false)
const doRefresh: Refresh = useCallback(async () => {
putToken(null)
if (!refreshing.current) {
refreshing.current = true
try {
@ -53,11 +52,12 @@ const RefreshProvider = ({ children }: PropsWithChildren) => {
} else if (error instanceof ApiError) {
console.error(error)
}
putToken(null)
refreshing.current = false
}
}
return null
}, [putToken, router])
}, [putToken])
return (
<RefreshContext.Provider