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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With