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

86
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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