45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
"use client"
|
|
|
|
import type React from "react"
|
|
import { createContext, useContext, useState, useEffect } from "react"
|
|
|
|
type AuthContextType = {
|
|
isLoggedIn: boolean
|
|
login: () => void
|
|
logout: () => void
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
|
|
|
export const useAuth = () => {
|
|
const context = useContext(AuthContext)
|
|
if (!context) {
|
|
throw new Error("useAuth must be used within an AuthProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
const [isLoggedIn, setIsLoggedIn] = useState(false)
|
|
|
|
useEffect(() => {
|
|
const storedLoginState = localStorage.getItem("isLoggedIn")
|
|
if (storedLoginState === "true") {
|
|
setIsLoggedIn(true)
|
|
}
|
|
}, [])
|
|
|
|
const login = () => {
|
|
setIsLoggedIn(true)
|
|
localStorage.setItem("isLoggedIn", "true")
|
|
}
|
|
|
|
const logout = () => {
|
|
setIsLoggedIn(false)
|
|
localStorage.removeItem("isLoggedIn")
|
|
}
|
|
|
|
return <AuthContext.Provider value={{ isLoggedIn, login, logout }}>{children}</AuthContext.Provider>
|
|
}
|
|
|