I'm sitting in my js file trying to upload but for some reason, I don't understand entirely. My :: myUid isn't updating. Can anyone tell me how to fix it and maybe even why it's the case that myUid isn't updating?
var myUid = '33';
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
window.myUid = user.uid;
// ...
} else {
// User is signed out.
// ...
}
// ...
});
function writeUserData() {
database.ref('users/').set({
profileID: myUid,
});
};
writeUserData();
Best regards, Sam
myUid
value is updated only when the callback for onAuthStateChanged
is executed asynchronously . By the time you invoke the writeUserData()
function on your main execution flow, the above callback may not be have been completed yet.
So a better approach would be to get rid of the global variable and invoke the writeUserData
function from the onAuthStateChanged
callback, passing the user uid as a parameter.
function writeUserData(userUid) {
database.ref('users/').set({
profileID: userUid,
});
};
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
writeUserData(user.uid);
// ...
} else {
// User is signed out.
// ...
}
// ...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.