Check if user is already existed in localStorage - javascript

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.

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

How I email implement in query on my code

This is a MongoDB API I create '/inventoryItems' this API already shows for all Inventory items
This is my back-end database FORM data
{ _id:2749d97592b4b1d084e20a2
supplierName:"carsale"
email:"imd572258#gmail.com"
brand:"audi"
quantity:"1"
price:"520"
description:"car want need want "
img:"https://res.cloudinary.com/dk0lorahh/image/upload/v1648239069/
}
How i do use const email = req.query.eamil
const query={email :email}
app.get("/inventoryItems", async (req, res) => {
const page= parseInt(req.query.page);
const size = parseInt(req.query.size);
**const email = req.query.email**
const query = {};
const cursor = inventoryItemsCollection.find(query);
let inventoryItems ;
if( page || size ){
inventoryItems = await cursor.skip(page*size).limit(size).toArray();
}else{
inventoryItems = await cursor.toArray();
}
res.send(inventoryItems);
});
**if i do like this**
const page= parseInt(req.query.page);
const size = parseInt(req.query.size);
const email = req.query.email
**const query = {email: email};**
const cursor = inventoryItemsCollection.find(query);
let inventoryItems ;
if( page || size ){
inventoryItems = await cursor.skip(page*size).limit(size).toArray();
}else{
inventoryItems = await cursor.toArray();
}
res.send(inventoryItems);
});
it's working find the email result but When mY Form data are not working not showing
showing empty
[]
I want a way how to do both works email results and my form results showing

pull out data from array in localStorage

I have a function that takes data from an input and saves it as data in an array during registration. Now I want another function to check during login if the data exists and if it matches. How can I do this using javascript only?
In short, I need a function that checks if the data entered by the user exists and if so, logs him in.
function saveData() {
let name, email, password;
name = document.getElementById("username").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
let user_records = new Array();
user_records = JSON.parse(localStorage.getItem("users"))
? JSON.parse(localStorage.getItem("users"))
: [];
if (
user_records.some((v) => {
return v.email == email;
})
) {
alert("Email wykorzystany");
} else {
user_records.push({
name: name,
email: email,
password: password,
});
localStorage.setItem("users", JSON.stringify(user_records));
}
}
I know that this is not how registration should be done. I am just doing it to learn new things.
this is a basic login, when you verify that the emmail and password are right, you can do wathever you want
function checkData() {
const name = document.getElementById('username').value;
const password = document.getElementById('password').value;
let user_records = JSON.parse(localStorage.getItem('users')) || [];
if (
user_records.find((user) => {
return user.name == name && user.password == password;
})
) {
alert('Logged in');
// do your things here
} else {
alert('wrong email or password');
// do your things here
}
}
<input id="username" />
<input id="password" />
<input type="submit" value="submit" onClick="checkData()" />
Extra:
This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world
function saveAndTestUser() {
// here use const as they are not updated
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Get all the records of the users
// prefer camelcase : not a rule though but it's better this way
const storedUsers = localStorage.getItem('users')
// if there are no stored users then assign empty array
// so that we don't get unexpected errors
const userRecords = storedUsers ? JSON.parse(storedUsers): []
// Checking if email already exists
if(userRecords.some(user => user.email === email)){
alert("user already exists")
return false; // stops the function execution
}
// If email doesn't exists then the code below will be executed
// Similar to if-else
// Add current record to existing records
const newRecords = [...storedUsers, {name, email, password}]
// Set the new record to storage
localStorage.setItem("users", JSON.stringify(newRecords));
}

Pass object value out of event listener scope

How can I pass the object value out of my event listener scope?
addbtn.onclick = function(){
const fName = firstName.value;
const lName = lastName.value;
const trSubject = trainerSubject.value;
let trainer = {
fName,
lName,
trSubject
};
};
You can rewrite your code to have trainer as a global variable and then set its values using your eventListener
And also, your trainer variable has a list of elements and is not in a key, value pair format, so I will assume you meant an array and fix that for you.
let trainer = [];
addBtn.addEventListener("click", () => {
const fName = firstName.value;
const lName = lastName.value;
const trSubject = trainerSubject.value;
trainer.push([fName, lName, trSubject]);
});
If you meant the trainer variable to be an object in the form of
let trainer = {
fName: "",
lName: "",
trSubject: ""
};
Then inside your event listener you can set the values of that object using trainer.fName = fName etc etc.

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

How to get just the first name when a user logs in using social media with firebase?

Here is the code that I am using to get the details of the user when they log in using google, facebook or twitter.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var uid = user.uid;
var phoneNumber = user.phoneNumber;
var providerData = user.providerData;
user.getToken().then(function(accessToken) {
console.debug('user', user);
document.getElementById('name').textContent = displayName;
document.getElementById("avatar").src = photoURL;
});
} else {
console.log('not logged in');
}
});
Then in the html by writing <p id="name"></p> the entire name of the user is displayed.
How do I display just the first name of the user?
You can do it like this;
document.getElementById('name').textContent = (displayName.split(' '))[0];
First and last name are available from most social providers just after you log in, but you will need to save them to your database as Firebase does not. What each provider calls first and last name varies, though.
Documentation at https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signinwithpopup
firebase.auth
.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then((user) => {
const firstName = user.additionalUserInfo.profile.given_name;
const lastName = user.additionalUserInfo.profile.family_name;
});
firebase.auth
.signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
.then((user) => {
const firstName = user.additionalUserInfo.profile.givenName;
const lastName = user.additionalUserInfo.profile.surname;
});

Categories

Resources