I’m working on a login form using local storage. I’ve narrowed the issue down to either on the first or second line. To be totally honest, I’m not comfortable using .includes or .key. Thanks.
if (i = 0; i < localStorage.length; i++) { if (localStorage.key(i).includes(username.value) != true) { if (username.value != "") { console.log("Your account has been created") localStorage.setItem(i, username.value) }
Advertisement
Answer
In case you want to store the list of usernames in localStorage, I will suggest you to store it in the form of JSON data as mentioned below rather than creating multiple key value pairs for each new users.
Add username to LocalStorage:
if(username.value !== '') { if(localStorage["users"]) { let users = JSON.parse(localStorage["users"]); users.push(username.value); localStorage["users"] = JSON.stringify(users); } else { localStorage["users"] = JSON.stringify([username.value]); } }
Get all username from LocalStorage:
let users = JSON.parse(localStorage["users"]);
Get username by name from LocalStorage:
let user = JSON.parse(localStorage["users"]).find(u => u === username.value);
Check if user exists
let isUserExists = localStorage["users"] && JSON.parse(localStorage["users"]).some(u => u === username.value);
Final Code: You can use the below code.
if(username.value !== '') { let isUserExists = localStorage["users"] && JSON.parse(localStorage["users"]).some(u => u === username.value); if(!isUserExists) { if(localStorage["users"]) { let users = JSON.parse(localStorage["users"]); users.push(username.value); localStorage["users"] = JSON.stringify(users); } else { localStorage["users"] = JSON.stringify([username.value]); } } }