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.
CodePudding user response:
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
.
CodePudding user response:
Check user to undefined
user && localStorage.setItem("token", user)