Reputation: 11
I'm currently developing a blog application.I use react js for frontend and node js for backend.I have this isAuthenticated method.
export const isAuthenticated = () => {
if (typeof window == 'undefined') {
return false;
}
if (localStorage.getItem('jwt')) {
return JSON.parse(localStorage.getItem('jwt'));
}
else {
return false;
}};
and I use it here
<li className="nav-item">
<Link
to={`/user/${isAuthenticated().user._id}`}
style={isActive(history, `/user/${isAuthenticated().user._id}`)}
className="nav-link"
>
{`${isAuthenticated().user.name}'s profile`}
</Link>
</li>
And it's giving me error of TypeError: Cannot read property '_id' of undefined in
to={/user/${isAuthenticated().user._id}
} this part
Please help I'm stocked I can't get the _id from backend I think but I can jwt token whenever I click the application in google chrome dev tools
Upvotes: 0
Views: 362
Reputation: 13692
Your function can not only return localStorage item but also can return false.
So make proper checks like this
isAuthenticated() ? (
<Link
to={`/user/${isAuthenticated().user._id}`}
style={isActive(history, `/user/${isAuthenticated().user._id}`)}
className="nav-link"
>
{`${isAuthenticated().user.name}'s profile`}
</Link>
) : (
<Link
to={`/login}`}
className="nav-link"
>
Login
</Link>
)
Upvotes: 0
Reputation: 535
You try to get object with user property from isAuthenticated function but it returns only string or boolean.
Upvotes: 1