File size: 1,207 Bytes
2251e03 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import { useState, useEffect } from 'react';
import { isUserRegistered } from '../utils/index.ts';
/**
* Custom hook for reactive authentication state
* Provides current authentication status and updates when it changes
*/
export const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(isUserRegistered());
useEffect(() => {
// Check authentication status on mount and when storage changes
const checkAuth = () => {
setIsAuthenticated(isUserRegistered());
};
// Listen for storage changes (when user_id is set/cleared)
const handleStorageChange = (e: StorageEvent) => {
if (e.key === 'user_id') {
checkAuth();
}
};
// Listen for custom auth events (for immediate updates after login/logout)
const handleAuthChange = () => {
checkAuth();
};
window.addEventListener('storage', handleStorageChange);
window.addEventListener('authChange', handleAuthChange);
// Initial check
checkAuth();
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('authChange', handleAuthChange);
};
}, []);
return { isAuthenticated };
};
|