I’m trying to set user data into the realtime database. To do that I want the uid of the current user who is logged in. But when I use the firebase.auth().currentUser.uid; I’m getting the previous uid.
Here’s the code:
JavaScript
x
67
67
1
// Your web app's Firebase configuration
2
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
3
var firebaseConfig = {
4
apiKey: "*",
5
authDomain: "*",
6
databaseURL: "*",
7
projectId: "*",
8
storageBucket: "*",
9
messagingSenderId: "*",
10
appId: "*",
11
measurementId: "*"
12
};
13
// Initialize Firebase
14
firebase.initializeApp(firebaseConfig);
15
16
//sign up the user
17
const auth = firebase.auth();
18
var user_info_reference = firebase.database();
19
20
document.getElementById('register-form').addEventListener('submit', submitInfo);
21
22
//signup function
23
const signupForm = document.querySelector('#register-form');
24
signupForm.addEventListener('submit', (e) => {
25
e.preventDefault();
26
27
const email = signupForm['email_up'].value;
28
const password = signupForm['pass_up'].value;
29
30
31
//auth with firebase
32
auth.createUserWithEmailAndPassword(email, password).then(cred => {
33
console.log(cred.user);
34
signupform.reset();
35
user_id = firebase.auth().currentUser.uid;
36
37
38
}).catch(function(error){
39
40
var errorcode=error.code;
41
var errormsg=error.message;
42
43
});
44
});
45
46
//saving user info
47
//submitting info about name
48
function submitInfo(e){
49
e.preventDefault();
50
51
//get values
52
var name = getInputval('name_up')
53
saveInfo(name);
54
55
//get id val
56
function getInputval(id){
57
return document.getElementById(id).value;
58
}
59
60
function saveInfo(name){
61
var new_user_info = user_info_reference.ref('user_info/'+ auth.currentUser.uid);
62
new_user_info.set({
63
name: name
64
});
65
}
66
}
67
Don’t mind the (*) in the config, I just don’t want to show that information.
Advertisement
Answer
If you want to get the UID of the current user right after they signed in, you can get if from cred
:
JavaScript
1
4
1
auth.createUserWithEmailAndPassword(email, password).then(cred => {
2
user_id = cred.user.uid;
3
4