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

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

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