I created a react component, to login into an app. When I try to get the name from localStorage and use it to add it as a string to a login navbar I get an error.
In My component is have this code:
const auth = localStorage.getItem("user");
and in navbar if I add this line:
<li> <Link onClick={logout} to="/signup"> Logout ({JSON.parse(auth).name}) </Link> </li>
more specifically:
{JSON.parse(auth).name}
I get this error:
"undefined" is not valid JSON SyntaxError: "undefined" is not valid JSON
2
Answers
This means the user doesn’t exist. You can check it by using this code:
The call the name const like this:
In provided code, auth is undefined, which means there’s no item in localStorage with the key "user". You can try this code:-
By applying this code,even if auth is undefined, the code won’t attempt to parse it, and you won’t encounter a "SyntaxError".