I’m developing a full-stack website using React.js for the frontend and Node.js for the backend. In the Navbar, there are two buttons: one for “Sign up” when a user first accesses the site without logging in, and another for “Dashboard” to display the user’s profile once they are logged in.
Problem Description
I use JWT (JSON Web Token) to verify the user and retrieve their information from the backend. After the authentication process completes, I can determine the user’s role from the JWT response. If the user token is valid, the “Dashboard” button appears in the Navbar; otherwise, the “Sign up” button is displayed.
The problem: When a request is sent to the backend, there is a delay before it confirms whether the user is in our system. During this delay, the “Sign up” button appears in the Navbar. After a few seconds, it switches to the “Dashboard” button if the user is authenticated.
Solution Needed
I need a way to handle this delay so that the “Sign up” button doesn’t appear briefly before switching to the “Dashboard” button. How can I improve this user experience?
1. **Initial Implementation:**
- I set up the Navbar with two buttons: "Sign up" and "Dashboard."
- When the user accesses the website, a request is sent to the backend to verify the JWT.
- Based on the JWT response, the Navbar updates to show either the "Sign up" button or the "Dashboard" button.
2. **Expected Behavior:**
- I expected the Navbar to initially display a loading state or nothing while the authentication check is in progress.
- Once the authentication check is complete, the Navbar should display the appropriate button ("Sign up" or "Dashboard") based on the JWT validation.
3. **Actual Result:**
- The "Sign up" button appears in the Navbar by default.
- After a delay, if the JWT is valid, the "Sign up" button switches to the "Dashboard" button.
- This causes a brief, confusing flicker where the "Sign up" button is visible before the "Dashboard" button appears.
### What I Expected
- I expected the Navbar to handle the authentication check seamlessly, without displaying the "Sign up" button during the verification process. Ideally, a loading indicator or a placeholder would be shown until the authentication status is confirmed.
### Actual Result
- The "Sign up" button is visible for a few seconds before switching to the "Dashboard" button if the user is authenticated, causing a confusing user experience.
### Solution Needed
- I need a way to implement a loading state or placeholder during the authentication check to avoid showing the "Sign up" button briefly before the authentication status is confirmed. This should make the user experience smoother and more intuitive.
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { verifyUser } from '../../redux/actions/authAction';
const ProtectedRouteHook = () => {
const dispatch = useDispatch();
const [userData, setUserData] = useState([]);
const [error, setError] = useState(true);
const [loading, setLoading] = useState(true);
const res = useSelector((state) => state.authReducer.verifyuser);
useEffect(() => {
setLoading(true);
dispatch(verifyUser());
setLoading(false);
}, []);
useEffect(() => {
if (loading === false) {
if (res.data) {
setLoading(true)
// if status is success set error false because ,this meaning the user trying to log is exist
if (res.status === 'success') {
localStorage.setItem('user',JSON.stringify(res.data))
setUserData(res.data)
setError(false)
}
// if status is fail set error true or not do any action ,this meaning there is problem in conn
if (res.status === 'fail') {
setError(true)
}
// if syatus is forbidden set error false ,meaning that there is confilct in JWT
if (res.data.status === 'forbidden') {
setError(false)
}
}
}
}, [res.data]);
return [
error?undefined:userData.role === 'OWNER' || userData.role === 'TEACHER', // isUser
error?undefined:userData.role === process.env.REACT_APP_ADMIN_CODE, // isAdmin
userData,
loading
];
};
export default ProtectedRouteHook;
import React, { useState ,useEffect} from 'react';
import { Col, Nav, Navbar, Container, Form } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import ProtectedRouteHook from '../../hooks/auth/protectedRoutedHook';
import Navbardropdown from './widgets/navbardropdown';
import NavBarButton from './widgets/navbarbutton';
import logo from '../../assets/images/logo.png';
import { useTranslation } from 'react-i18next';
function NavBar() {
const { t, i18n } = useTranslation();
const [isUser, isAdmin, data, loading] = ProtectedRouteHook();
const [expanded, setExpanded] = useState(false);
const toggleLanguage = () => {
const newLanguage = i18n.language === 'en' ? 'ar' : 'en';
i18n.changeLanguage(newLanguage);
localStorage.setItem('language', newLanguage);
};
useEffect(() => {
const storedLanguage = localStorage.getItem('language');
if (storedLanguage) {
i18n.changeLanguage(storedLanguage);
}
}, [i18n]);
return (
<Navbar collapseOnSelect expand="lg" className="navbar" expanded={expanded}>
<Container>
<Link to="/" className="navbar-brand">
<img style={{ height: '80px', width: '100px' }} alt="logo" src={logo} />
</Link>
<Form.Check
type="switch"
id="language-switch"
label={i18n.language === 'en' ? 'ع' : 'EN'}
className="mx-2"
style={{ color: 'white' }}
onChange={toggleLanguage}
/>
<Navbar.Toggle
aria-controls="responsive-navbar-nav"
onClick={() => setExpanded(!expanded)}
style={{ color: 'white', backgroundColor: 'white', marginLeft: 'auto' }}
/>
<Navbar.Collapse id="responsive-navbar-nav">
<Col
xs={6}
md={6}
className={`d-flex justify-content-end mb-2 mb-md-0 ${i18n.language === 'ar' ? 'rtl' : ''}`}
style={{ marginLeft: '100px' }}
>
<Nav className="d-flex justify-content-center">
<Nav.Link href="/" className="link mx-md-3" style={{ fontFamily: i18n.language === 'en' ? 'Poppins' : 'Cairo' }}>
{t('navbar.home')}
</Nav.Link>
<Nav.Link href="/about-us" className="link mx-lg-3" style={{ fontFamily: i18n.language === 'en' ? 'Poppins' : 'Cairo' }}>
{t('navbar.aboutUs')}
</Nav.Link>
<Nav.Link href="/places" className="link mx-lg-3" style={{ fontFamily: i18n.language === 'en' ? 'Poppins' : 'Cairo' }}>
{t('navbar.ourPlaces')}
</Nav.Link>
{data.role === 'OWNER' && (
<Nav.Link href="/hall-add" className="link mx-lg-3" style={{ fontFamily: i18n.language === 'en' ? 'Poppins' : 'Cairo' }}>
{t('navbar.addPlace')}
</Nav.Link>
)}
</Nav>
</Col>
<Col
xs={6}
md={6}
className="d-flex justify-content-center px-xs-4 px-md-4"
style={{ marginRight: '-40px' }}
>
{isUser && loading ? (
isUser || isAdmin ? <Navbardropdown isUser={isUser} /> : null
) : (
!isUser || !isAdmin ? <NavBarButton /> : null
)}
</Col>
</Navbar.Collapse>
</Container>
</Navbar>
);
}
export default NavBar;