()
| 8 | * @returns An object containing the user, and whether the user is authenticated |
| 9 | */ |
| 10 | const useAuthState = () => { |
| 11 | // Get user from local storage |
| 12 | const localUser = localStorage.getItem("user"); |
| 13 | const initialUser = localUser ? JSON.parse(localUser) : null; |
| 14 | |
| 15 | const [user, setUser] = useState<User | null>(initialUser); |
| 16 | const [isAuthenticated, setIsAuthenticated] = useState<boolean>( |
| 17 | initialUser?.emailVerified || false, |
| 18 | ); |
| 19 | const [isLoading, setIsLoading] = useState(true); |
| 20 | |
| 21 | useEffect(() => { |
| 22 | // This listener will be called whenever the user's sign-in state changes |
| 23 | const unsubscribe = auth.onAuthStateChanged((currentUser) => { |
| 24 | setUser(currentUser); |
| 25 | setIsLoading(false); |
| 26 | localStorage.setItem("user", JSON.stringify(currentUser)); |
| 27 | }); |
| 28 | |
| 29 | // Cleanup subscription on unmount |
| 30 | return () => unsubscribe(); |
| 31 | }, []); // Empty array ensures this effect runs only once on mount |
| 32 | |
| 33 | useEffect(() => { |
| 34 | setIsAuthenticated(user?.emailVerified || false); |
| 35 | localStorage.setItem("user", JSON.stringify(user)); |
| 36 | }, [user]); |
| 37 | |
| 38 | return { user, isAuthenticated, isLoading }; |
| 39 | }; |
| 40 | |
| 41 | export default useAuthState; |
no outgoing calls
no test coverage detected