I'm trying to seed my Firebase with a list of initial users in the web app. This should be a two-step process:
createUserWithEmailAndPassword()
method.collection.add()
method.// Initialize Firebase:
var db = firebase.initializeApp(config).firestore();
// Function to add a new user:
function add(email) {
firebase.auth().createUserWithEmailAndPassword(email, 'password')
.then(function (user) {
console.log('User created:', email, user.user.uid);
return db.collection('users').add({
email: email,
uid: user.user.uid
});
})
.then(function () {
console.log('Document created:', email);
})
.catch(function (error) {
console.error('Could not create user/document:', error);
});
}
// Seed database with random users:
for (var i = 0; i < 10; ++i) {
add(i + '@foo.bar');
}
The code from the previous section doesn't work. My expectation is that it should create 10 users, and add 10 corresponding documents to the database on success. However, it adds only part of documents (1-3) to the database, even though the users are created properly.
I came up with some ideas on the possible reasons why this code doesn't work:
createUserWithEmailAndPassword()
method not only creates a new user, but also performs an automatic sign in. Probably, this could lead to some kind of race condition.createUserWithEmailAndPassword()
method returns a promise with a UserCredential
object of a newly signed up user (I believe). However, I might be wrong, and this object represents a signed in user which can be the reason for the race condition from the previous point.then()
nor catch()
are called.Here is the excerpt from the Firebase support answer:
Each time a new user is created with Auth, it sets the newly created user as the current user of the application. Whenever Firestore detects that a user change has occurred, it closes all outstanding streams and cancels any requests in flight.
This totally makes sense and explains the behavior.