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

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

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