Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
Navigation logout button and cart only updates after a refresh. React JS

I have this app, where i want to display an logout button in the navigation when the user is logged in. But for some reason, the button only shows after i do a refresh of the page, not when the user is logged in.

Also the same thing happens for the cart number update (on the same component), it only update the number after a refresh. Here i am trying to get number from local storage. I made a seperat component for the "buy" button since i want it on all items.

I need some help please, what am i doing wrong?

Here is Navigation component:


function Navigation() {


    const [loggedIn, setLoggedIn] = useState(JSON.parse(localStorage.getItem("games")));


    let history = useHistory();

    function logOut() {

        localStorage.clear('Email', 'Password');


        history.push('/')
    }



    function getCartItems() {

        if (localStorage.getItem("games")) {
            return JSON.parse(localStorage.getItem("games")).length
        }
        else {
            return 0;
        }
    };


    return (
        <div className="navgation_container">
            <div className="navigation_cartcontainer">
                <img className="navigation_logo" src={logo} alt="logog bits&bots" />
                {loggedIn ? (
                    <div className="navigation_cartimg">
                        <img className="navigation_cart" src={cart} alt="cart for the page" />
                        <p className="navigation_numberitems">{getCartItems()}</p>
                        <button className="navigation_logout" onClick={logOut}>Log out</button>
                    </div>
                ) : (
                    <div>Test</div>
                )}
            </div>
        </div>

    );
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Using useState might help you and pass in the value from local storage to useState as shown :

useEffect( ()=>{
      setLoggedIn(data_from_local_storage);
      
   }[data_from_local_storage]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda