Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing user data in an object in local storage

Tags:

javascript

I am doing a school project on creating a web site. I have managed to save user data into local storage upon signing up for an account. when I tried with the following codes yesterday, the codes could work: the key 'currentUser' would appear in the local storage after I have logged in as a user. However, after I cleared my local storage (too many users in array) and I re-run the codes again the currentUser would no longer show up in local storage. Here are my codes: From edit profile page: `

<script>
var currentUser=null;
document.addEventListener("DOMContentLoaded",loadUserData);

function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);

    }
}
</script>

The above codes plus this from the login html shows the currentUser as the key in local Storage (should only appear upon logging in as current user) From login page:

    function checkUser(ev) {
          ev.preventDefault();
          var status=false;

          var username = document.getElementById("username").value;
          var password = document.getElementById("password").value;


          for(var i=0;i<userList.length;i++) {
            var u=userList[i];
            console.log(u.username);
            console.log(u.password);
            if (u.username==username && u.password==password){
            status=true;
                            localStorage.setItem("currentUser",username);
            currentUser=userList[i];
            break;
            }
          }

          if (status==true){
            location.href="EditProfile.html";
          }

     }

What showed up in the local storage was just the key currentUser, but it's value is empty. I want the data info of the currentUser shown in local storage after the user has logged in, so that I can display the user details in the edit profile and profile page.

What I expected to see in local storage:

key             value
currentUser    {"username":"staff3","name":"stella ","password":"123","rpassword":"123,"email":"[email protected]"}

What showed in local storage:

key           value
currentUser    //nth showed up here 
like image 752
blackJack Avatar asked Aug 06 '16 08:08

blackJack


1 Answers

Here is the problem:

LocalStorage only store strings. If you want to store an object, you can use

 JSON.stringify(object)

So in your case, you need:

localStorage.setItem("currentUser",JSON.stringify(userList[i]));

Hope that helps!

like image 118
Duly Kinsky Avatar answered Sep 18 '22 04:09

Duly Kinsky