Managing Component Visibility Delays in React.js


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;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật