简体   繁体   中英

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.

  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 .

检查用户未定义

user && localStorage.setItem("token", user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM