Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!