Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Navbar to navigate back to the home screen #69

Merged
merged 1 commit into from
Mar 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions src/components/Navbar.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import { useNavigate } from "react-router";
import { useNavigate, useLocation } from "react-router";
import { auth } from "../firebase/config";
import { onAuthStateChanged } from "firebase/auth";
import { ModalsContext } from "../contexts/ModalsProvider";
Expand All @@ -10,28 +10,36 @@ const Navbar = ({ admin }) => {
const openModal = useContext(ModalsContext).openModal;
const navigate = useNavigate();
const [user, setUser] = useState("");
const [buttonText, setButtonText] = useState("Sign up");
const [authButtonText, setAuthButtonText] = useState("Sign up");
const [adminButtonText, setAdminButtonText] = useState("Admin");
const location = useLocation();

useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user && user.displayName != null) {
setUser(`Hi ${user.displayName}`);
setButtonText("Sign out");
setAuthButtonText("Sign out");
}
});

// Clean up the onAuthStateChanged listener when the component unmounts
return () => unsubscribe();
}, [user.displayName]);

const handleNavigate = () => {
navigate(import.meta.env.BASE_URL + "admin");
const handleAdmin = () => {
if (location.pathname.includes("admin")) {
navigate(import.meta.env.BASE_URL);
setAdminButtonText("Admin");
} else {
navigate(import.meta.env.BASE_URL + "admin");
setAdminButtonText("Home");
}
};

const handleSignInOut = () => {
const handleAuth = () => {
if (user) {
setUser("");
setButtonText("Sign up");
setAuthButtonText("Sign up");
} else {
openModal(ModalTypes.SIGN_UP);
}
Expand All @@ -53,13 +61,9 @@ const Navbar = ({ admin }) => {
<div className="row row-cols-auto">
<div className="navbar-brand">{user}</div>
{admin && (
<button onClick={handleNavigate} className="btn btn-secondary me-2">
Admin
</button>
<button onClick={handleAdmin} className="btn btn-secondary me-2">{adminButtonText}</button>
)}
<button onClick={handleSignInOut} className="btn btn-secondary me-2">
{buttonText}
</button>
<button onClick={handleAuth} className="btn btn-secondary me-2">{authButtonText}</button>
</div>
</div>
</nav>
Expand Down
Loading