skip to Main Content

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


  1. This means the user doesn’t exist. You can check it by using this code:

    const auth = localStorage.getItem("user");
    const name = auth ? JSON.parse(auth).name : "";
    

    The call the name const like this:

    <li>
      <Link onClick={logout} to="/signup">
        Logout ({name})
      </Link>
    </li>
    
    Login or Signup to reply.
  2. In provided code, auth is undefined, which means there’s no item in localStorage with the key "user". You can try this code:-

    const auth = localStorage.getItem("user");
    
    const userName = auth ? JSON.parse(auth).name : null;
    
    <li>
      <Link onClick={logout} to="/signup"> Logout ({userName}) </Link>
    </li>
    

    By applying this code,even if auth is undefined, the code won’t attempt to parse it, and you won’t encounter a "SyntaxError".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search