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

135
Views
LocalStorage does not persist

I have been trying to persist my token in the localStorage but everytime I referesh the page, the value turns to undefined.

Here is my code from App.tsx. I am using redux in my project but persisting using redux throws plenty of type errors. That is why I am going with local storage.

  const [isLoggedIn, setIsLoggedIn] = useState('');
  // @ts-ignore
  const user = useAppSelector(state=>state.user.currentUser.token);
  useEffect(()=>{
    const getToken = localStorage.getItem("token");
    if(getToken){
      setIsLoggedIn(getToken)
    }
  },[])

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

For extra reference, these are my routes

        <Route path="/userProfile" element={<UserProfile />} />
        <Route path="/login" element={user ? <Navigate to="/" /> : <Login />} />
        <Route path="/cart" element={<Cart />} />
        <Route path="/" element={<Home />} />
        <Route path="/product/:id" element={<SingleProduct />} />       

So far I have tried all that I know but I am still not able to figure out the root problem.

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

Your problem is from the above useEffect. Although it has dependency user (which is listening to user state changes), it's called when you render the component for the first time.

I'd propose you should add a condition to that useEffect like below

  useEffect(()=>{
    if(user) {
       localStorage.setItem("token", user)
    }
  },[user])

That would help you to prevent calling setItem with an undefined value of user.

about 4 years ago · Santiago Gelvez Report

0

Check user to undefined

user && localStorage.setItem("token", user)
about 4 years ago · Santiago Gelvez 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!