I have created my app file which turns an isAuthenticated
variable to true on a successful login connection. I have verified that the Firebase API call is working correctly as only upon entry of a valid username and password does my program shift to the /admin page.
I want my header bar to hide the login button after a successful login but it is not working as my isAuthenticated
variable turns to undefined once I pass it in instead of turning to true
. I know this is happening because I am putting a console.log statement in my header file to print out the value of the isAuthenticated
variable. In my Header.js
file, I want to use this variable to control whether or not the login button appears.
This is my code for the App.js
and Header.js
files:
import './App.css';
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import Header from './Header';
import LoginForm from './LoginForm';
import AdminPage from './AdminPage';
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
//
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
function HomePage() {
const navigate = useNavigate();
const auth = getAuth();
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setIsAuthenticated(true);
navigate('/admin');
} else {
setIsAuthenticated(false);
}
});
return () => unsubscribe();
}, [auth, navigate]);
const handleLogin = async (username, password) => {
try {
await signInWithEmailAndPassword(auth, username, password);
console.log('Login successful');
navigate('/admin'); // Navigate to the admin page on successful login
} catch (error) {
console.log(error.message);
}
};
return (
<div className="App">
<Header
isAuthenticated={isAuthenticated}
handleLoginFormSubmit={handleLogin} // Pass handleLogin as a prop
/>
</div>
);
}
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/admin" element={<AdminPage />} />
</Routes>
</Router>
);
}
export default App;
import React, { useState } from 'react';
import LoginForm from './LoginForm';
function Header({ isAuthenticated, handleLoginFormSubmit }) {
const [showLoginForm, setShowLoginForm] = useState(false);
const handleLoginButtonClick = () => {
setShowLoginForm(true);
};
return (
<header className="App-header">
<h1 className="App-title">Family Wordle</h1>
{isAuthenticated ? null : (
<>
{!showLoginForm ? (
<button className="App-button" onClick={handleLoginButtonClick}>
Admin Login
</button>
) : (
<LoginForm handleLogin={handleLoginFormSubmit} /> // Updated prop name
)}
</>
)}
</header>
);
}
export default Header;