Reputation: 45
I have the following code and I need to extract the password from the userData object that appears in the console as follows:
-MeL7hm5pU3RGhvXnYlR: {name: "wed", password: "wed", userName: "wed"}
My code is
const Login = e => {
e.preventDefault();
firebaseDb.child("authors").orderByChild("userName").equalTo(userName).once("value", snapshot => {
if (snapshot.exists()) {
const userData = snapshot.val();
console.log(userData)
if(userData.password !== password)
window.alert("Username or Password are wrong!");
else {
history.push("/AuthorForm");
localStorage.setItem("author-info",
JSON.stringify(userName));
}
}
});
}
Upvotes: 1
Views: 1090
Reputation: 598847
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to handle the fact that it gets a list of results, typically by using Firebase's built-in forEach
method:
firebaseDb.child("authors").orderByChild("userName").equalTo(userName).once("value", results => {
if (results.exists()) {
results.forEach((snapshot) => {
const userData = snapshot.val();
console.log(userData)
if(userData.password !== password) {
window.alert("Username or Password are wrong!");
}
else {
history.push("/AuthorForm");
localStorage.setItem("author-info",
JSON.stringify(userName));
}
});
}
});
Upvotes: 0
Reputation: 50840
Note: Using this way is not secure. Anyone making a login request will get the password of that username because you are doing client side validation.
Apart from that, your object looks like:
{
"-MeL7hm5pU3RGhvXnYlR": {
name: "wed",
password: "wed",
userName: "wed"
}
}
You can use Object.values()
to access the name and password fields.
const {name, password, userName} = Object.values(thatObjectAbove)[0]
console.log(name, password, userName)
Upvotes: 1