Search code examples
javascripttypescriptlocal-storage

Extract username from localStorage Typescript/JavaScript


I m still new with Typescript, i want to output only username from this localStorage:

localStorage.getItem('currentUser')

which currently outputing: {"username":"root","password":"root"}

How can i do it ?


Solution

  • Short answer: Convert the string back to an object using JSON.parse:

    var user = JSON.parse(localStorage.getItem('currentUser'));
    console.log(user.username);
    

    (Note: this applies to JavaScript in general, not just TypeScript)


    Details

    Items are stored in localStorage as strings. So to save an object in localStorage, you convert it to a string using JSON.stringify(obj). (Whoever saved your user object to localStorage likely used this method.)

    To convert back to an object, use JSON.parse(str). Note that this can throw an exception if the string isn't a valid JSON representation of an object.

    Example of all that with your user object (it's also valid JavaScript if you remove type declarations):

    interface IUser {
      username: string;
      password: string; // please don't do this in real code
    }
    
    function saveCurrentUser(user: IUser): void {
      localStorage.setItem('currentUser', JSON.stringify(user));
    }
    
    function getCurrentUser(): IUser {
      var userStr = localStorage.getItem('currentUser');
      try {
        return JSON.parse(userStr);
      } catch (ex) {
        return null; // or do some other error handling
      }
    }
    
    var user = { username: 'root', password: 'root' };
    saveCurrentUser(user);
    
    // elsewhere...
    var savedUser = getCurrentUser();
    if (savedUser) {
      console.log('Current user: ' + savedUser.username);
    } else {
      console.log('Current user not found');
    }