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

122
Visualizações
Why's the button displayed only when refreshing the page?

I want the logout button to show up only when the user's logged in. It kind of works now but it's not working the way it should.

With the code below, the logout button shows up when the user's logged in only if the page's refreshed. That's because upon the <App/> component being loaded, the <Navbar/> component mounted along with it.

But how can I make it so that even if <Navbar/>'s loaded, it can still be possible to manipulate when the button can appear based on if the auth token is not null?

Here's App.js:

const App = () => {
let [logoutButtonFlag, setLogoutButtonFlag] = useState(false);
let authToken = localStorage.getItem('token');

useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    } 
}, [authToken]);

return (
    <>
      <Navbar logoutButtonFlag={logoutButtonFlag}/>
    </>
  );
}

export default App;

Here's Navbar.js:

const Navbar = (props) => {
    return ( 
      {!props.logoutButtonFlag ? null : <button className="learn-more">Logout</button>}
    );
};

export default Navbar;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you are providing a non-state variable to the list of states that useEffect hook 'listen' to, so it will not run again after you change its value.

const [authToken, setAuthToken] = useState(localStorage.getItem('token'));

and when you update the local storge "token" also update authToken to the same value. and your useEffect will retrigger on authToken change because now its a state

useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    } 
}, [authToken]);

The reason way only on refresh it was updating is because the value of the "token" in local storage was changed already.

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