mirror of
https://github.com/TurTaskProject/TurTaskWeb.git
synced 2025-12-19 22:14:07 +01:00
39 lines
1016 B
JavaScript
39 lines
1016 B
JavaScript
import React, { createContext, useContext, useState, useEffect } from "react";
|
|
|
|
const AuthContext = createContext();
|
|
|
|
export const AuthProvider = ({ children }) => {
|
|
const [isAuthenticated, setIsAuthenticated] = useState(() => {
|
|
const access_token = localStorage.getItem("access_token");
|
|
return !!access_token;
|
|
});
|
|
|
|
useEffect(() => {
|
|
const handleTokenChange = () => {
|
|
const newAccessToken = localStorage.getItem("access_token");
|
|
setIsAuthenticated(!!newAccessToken);
|
|
};
|
|
|
|
handleTokenChange();
|
|
|
|
window.addEventListener("storage", handleTokenChange);
|
|
|
|
return () => {
|
|
window.removeEventListener("storage", handleTokenChange);
|
|
};
|
|
}, []);
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useAuth = () => {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error("useAuth must be used within an AuthProvider");
|
|
}
|
|
return context;
|
|
}; |