47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
|
|
'use client'
|
||
|
|
|
||
|
|
import { createContext, useContext, useEffect, useState } from 'react'
|
||
|
|
import Loading from '../components/layout/shared/Loading'
|
||
|
|
|
||
|
|
type AuthContextType = {
|
||
|
|
isAuthenticated: boolean
|
||
|
|
token: string | null
|
||
|
|
currentUser: string | null
|
||
|
|
}
|
||
|
|
|
||
|
|
const AuthContext = createContext<AuthContextType>({
|
||
|
|
isAuthenticated: false,
|
||
|
|
token: null,
|
||
|
|
currentUser: null
|
||
|
|
})
|
||
|
|
|
||
|
|
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
|
||
|
|
const [token, setToken] = useState<string | null>(null)
|
||
|
|
const [currentUser, setCurrentUser] = useState<string | null>(null)
|
||
|
|
const [isInitialized, setIsInitialized] = useState(false)
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const savedToken = localStorage.getItem('authToken')
|
||
|
|
const savedUser = localStorage.getItem('user')
|
||
|
|
if (savedToken) setToken(savedToken)
|
||
|
|
if (savedUser) setCurrentUser(savedUser)
|
||
|
|
setIsInitialized(true)
|
||
|
|
}, [])
|
||
|
|
|
||
|
|
if (!isInitialized) return <Loading />
|
||
|
|
|
||
|
|
return (
|
||
|
|
<AuthContext.Provider
|
||
|
|
value={{
|
||
|
|
isAuthenticated: !!token,
|
||
|
|
token,
|
||
|
|
currentUser
|
||
|
|
}}
|
||
|
|
>
|
||
|
|
{children}
|
||
|
|
</AuthContext.Provider>
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useAuth = () => useContext(AuthContext)
|