Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda