Reputation: 115
I am using firebase and I have run into an issue. What I am trying to do is allow a user to sign up, but to check the account doesn't already exist, I want to retrieve all of the usernames from firestore and then search through them to see if their proposed username already exists. Here is my code to do this:
document.querySelector("#form1").addEventListener("submit", e => {
e.preventDefault();
var users;
firestore.collection("users").get().then(querySnapshot => {
users = querySnapshot.docs.map(doc => doc.data());
console.log(users);
});
console.log(users);
});
So I know that when I try to do console.log(users) for the second time, the function above may not have completed its execution which is why when I log it to the console I see "undefined". How can I change my code so that the second console.log(users) waits for the function above to complete?
I tried looking into this and found some stuff to do with "async" and "wait" but I couldn't figure out how to make these work in my code. Maybe that could be the solution?
Upvotes: 0
Views: 66
Reputation: 7388
I can't warn you enough to not get all users
to check if one of them has the same username. I can strongly recommend to query for a single user with the same username:
document.querySelector("#form1").addEventListener("submit", async (e) => {
e.preventDefault();
const theEnteredUsername = ""; // get it from somewhere
// Create a reference to the cities collection
var ref = firestore.collection("users");
// Create a query against the collection.
var query = await ref.where("username", "==", theEnteredUsername).get();
if (query.empty) {
//you can use the username
} else {
//username taken!!!
}
});
Othervise your Firebase bill would be grow extremely with the increase of users in your app.
Upvotes: 1