Hello World Hello World - 4 months ago 23
Javascript Question

Storing user data in an object in local storage

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":"g@gmail.com"}


What showed in local storage:

key value
currentUser //nth showed up here

Answer

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!