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

79
Views
React, render component based on localStorage changes

I am trying to make an authentication system. Users can sign in and sign out via the top nav bar. The username will store in the local storage. I can find 'user' in my local storage after sign in, and it's gone after signing out.

But it seems that the useEffect doesn't work properly, so the top bar doesn't change accordingly. Any help is appreciated.

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(true);

  useEffect(() => {
    function checkUserData() {
      const user = localStorage.getItem("user");

      if (user) {
        setIsLoggedIn(true);
      }
    }
    window.addEventListener("storage", checkUserData);

    return () => {
      window.removeEventListener("storage", checkUserData);
    };
  }, []);

  return (
    <Router>
      <div className="container">
        <TopBar
          logout={() => {
            localStorage.removeItem("user");
          }}
          loginStatus={isLoggedIn}
        />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route
            path="/sign-in/"
            element={
              <SignIn
                toggleLoggedIn={(user) => {
                  localStorage.setItem("user", user);
                }}
              />
            }
          />
        <Footer />
      </div>
    </Router>
  );
}
function TopBar(props) {
  return (
    <div>
      <AppBar>
        <Toolbar >
          <Box />

          <Box>
            {props.loginStatus ? (
              <Link
                href="/"
                onClick={props.logout}
                component="button"
              >
                {"Sign Out"}
              </Link>
            ) : (
              <>
                <Link
                  href="/sign-in/"
                >
                  {"Sign In"}
                </Link>
                <Link
                  href="/sign-up/"
                >
                  {"Sign Up"}
                </Link>
              </>
            )}
          </Box>
        </Toolbar>
      </AppBar>
      <Toolbar />
    </div>
  );
}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Change logout and toggleLoggedIn functions as below. You need to dispach the storage event, because normally, a storage change is not noticed in the same document that's is making the changes.

() => {
  localStorage.removeItem("user");
  window.dispatchEvent(new Event("storage"));
}
(user) => {
 localStorage.setItem("user", user);
 window.dispatchEvent(new Event("storage"));
}

Then change checkUserData as below, to handle the else case, and change isLoggedIn to false.

function checkUserData() {
  const user = localStorage.getItem("user");
  if (user) {
    setIsLoggedIn(true);
  }else{
    setIsLoggedIn(false);
  }
}

And finally change your isLoggedIn definition as below, so you set the login state dynamically according to what's in the storage from previous visit:

const [isLoggedIn, setIsLoggedIn] = useState(localStorage.getItem("user") ? true : false);
about 4 years ago · Santiago Trujillo Report

0

You don't change the boolean isLoggedIn. So the navbar don't know when to update.

You have to do something like this :

if (user) {
  setIsLoggedIn(true);
} else {
  setIsLoggedIn(false);
}

or something on unmount like

useEffect(() => {return () => setIsLoggedIn(false)}, []);

I don't have the context of your application, but the main logic is to pass this boolean to false when user is not loggedin.

Also, I recommend you to externalize this logic via a hook for example "useAuthentication()". So the logic is separated from the render.

about 4 years ago · Santiago Trujillo Report

0

Note: The storage event is only triggered when a window other than itself makes the changes.

I found this on https://www.w3schools.com/jsref/event_storage_url.asp

about 4 years ago · Santiago Trujillo 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!