check if the user has already been in local storage

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) {

  //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

  //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>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top