Check if user is already existed in localStorage

Viewed 308

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");

const btnSignup = document.getElementById("btn-signup");

btnSignup.onclick = function () { // when mouse click "signup" button
    const first_name = firstName.value; // getting the value of firstName and so on..
    const last_name = lastName.value;
    const e_mail = newEmail.value;
    const pass_word = newPassword.value;

    if (first_name && last_name && e_mail && pass_word) {
 
        //set user input into JSON
        let user_data = {
            firstName: first_name,
            lastName: last_name,
            email: e_mail,
            password: pass_word
        }
        
        //get to localstorage if there is existing user ||or make empty array[]
        let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
        
        //ipush ang new user sa array
        clientsArr.push(user_data);

        //save to localstorage
        localStorage.setItem('users', JSON.stringify(clientsArr));
    }
        // location.reload();
        else if (user_data === localStorage.getItem('users')) { // THIS IS THE CODE THAT I AM TRYING
            alert("User already existed");
        } 
};

i am trying to put an error message something on the screen or alert thingy on the browser, this code actually works, the problem is how to identify if there is existing user inside the local storage. what i'm trying to say is, your "login" will not accept if there is existing user inside the memory. thank you! I put a comment to the code that i'm trying to run.

2 Answers

A few points:

  • JavaScript compares objects by memory reference (location on RAM).
  • let variables are bound to the lexical scope {}. Hence, user_data will not be available in the second else if statement.
  • Bonus: use the early exiting to keep the code clean.
  • Use a unique identifier such as an id. In the example, I am converting the objects to a string and compare them.

// Fields
const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
// Button
const btnSignup = document.getElementById("btn-signup");

function signUp() {

  const first_name = firstName.value;
  const last_name = lastName.value;
  const e_mail = newEmail.value;
  const pass_word = newPassword.value;

  // If either of the values is empty
  if (!first_name || !last_name || !e_mail || !pass_word) {
    return;
  }

  //set user input into JSON
  let user_data = {
    firstName: first_name,
    lastName: last_name,
    email: e_mail,
    password: pass_word
  }
  
  // convert to string
  let user_data_str = JSON.stringify(user_data)

  //get to localstorage if there is existing user ||or make empty array[]
  let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
  
  // Convert to string
  
  // Search the list if 
  const userExists = clientsArr.find(user => JSON.stringify(user) === user_data_str);
  
  if (userExists) {
    return alert('User already exists')
  }
    
  //ipush ang new user sa array
  clientsArr.push(user_data);

  //save to localstorage
  localStorage.setItem('users', JSON.stringify(clientsArr));

}
// Attach listener
btnSignup.addEventListener('click', signUp);
<input id="firstName" />
<input id="lastName" />
<input id="newEmail" />
<input id="newPassword" />
<button id="btn-signup">Sign up</button>

If you are trying to check if user already exists before adding to the "users" in the localStorage, you could do something like:

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");

const btnSignup = document.getElementById("btn-signup");

btnSignup.onclick = function () {
    const first_name = firstName.value;  
    const last_name = lastName.value;
    const e_mail = newEmail.value;
    const pass_word = newPassword.value;

    // Only get localstorage item once
    let clientsArr = JSON.parse(localStorage.getItem('users')) || [];

    // Only execute those lines if we have the data that we need
    if (first_name && last_name && e_mail && pass_word) {
 
        let user_data = {
            firstName: first_name,
            lastName: last_name,
            email: e_mail,
            password: pass_word
        }
        // Check if the user already exists to show an alert or add it to the list
        if(clientsArr.includes(user_data)) {
            alert("User already existed");
        } else {
             clientsArr.push(user_data);
             localStorage.setItem('users', JSON.stringify(clientsArr));
        }

    }

};
Related