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

114
Vistas
How can I use local Storage with the login functionality in react

I am trying to create a login functionality where if the user is logged in he/she should be redirected to /health page but if he/she is not logged in , the user should be automatically redirected to /login page. While doing this I came across the concept of local storage I understood and tried implementing it. However, it is not fetching the desired results.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

From what I can tell you are missing initializing your isLog state from localStorage. After a user authenticates you set the storage and redirect to the "/health" route, but if a user is already logged in and reloads the page, the App will reinitialize its isLog state back to false.

Using a state lazy initializer function you can read the localStorage for the isLog key and set the initial state.

const [isLog, setState] = useState(() => {
  return !!JSON.parse(localStorage.getItem("isLog"));
});

Edit how-can-i-use-local-storage-with-the-login-functionality-in-react

You can also simplify your redirect logic by moving it below all your routes other then the "404" match all routes.

Example:

<Switch>
  <Route path="/login">
    <Login isLogIn={handleLogin} />
  </Route>
  <Route path="/health" component={Health} />
  <Route path="/useradmin"  component={UserAdmin} />
  <Redirect exact from="/" to={isLog ? "/health" : "/login"} />
  <Route path="*">NOT FOUND</Route>
</Switch>
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