Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!