Reputation: 33
i'm trying to get user UID in the place of auto generated document ID in Firebase/Firestore but can't get it because of this error
TypeError: firebase.auth(...).currentUser is null
this is my index.js file:-
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
//alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// Getting user id
var uid = firebase.auth().currentUser.uid;
//User Data Insertion
if(uid !=null){
db.collection("users").doc(uid).add({
UserName: txtname,
Email: txtEmail,
Password: txtPass
})
// .then(function(uid) {
// console.log("Document written with ID: ", uid);
// })
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
}
Upvotes: 3
Views: 12443
Reputation: 41
You can relate the below example and generate your code
Here "_email","_password","_city","_phone"
are variables for
onSaved: (value) => _email = value
taken from TextFormField()
function
Code:
String userId = await widget.auth.createUserWithEmailAndPassword(_email, _password);
print('Registered user: $userId');
final new_user = await FirebaseFirestore.instance.collection('users').doc(userId).
set({"UserUID":'$userId',"Email":_email,"Password":_password,"City":_city,"Phone
Number":_phone});
Upvotes: 0
Reputation: 4196
Before I present you with my answer, BEWARE cloud functions do take unpredictable amount of time to process. So if you need to immediately start using the data stored in the users collection, maybe it's not the right method for you to take.
Using firebase cloud functions..
exports.createUser = functions.auth.user().onCreate((user) => {
const userMap = {
uid: user.uid,
email: user.email,
};
return admin.firestore().collection('user').doc(user.uid).set(userMap);
});
Upvotes: 1
Reputation: 335
Since firebase.auth().createUserWithEmailAndPassword(...)
is an async function, you have to wait for it to resolve before continuing.
You can try this:
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail,txtPass)
.then(function (user) {
// insert any document you want here
})
.catch(function(error) {
// handle error here
});
}
Upvotes: 6