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 }; };