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

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

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 Relatório

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 Relatório

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