I am trying to save the "score" variable to the "highscore" field in my cloud firestore database for my user but the change only appears after I sign in again using google. Everytime I sign in, there is also a new document being created even though I am signing in with the same google account. I did this while updating a standard collection like "displayName" but the custom collection I have set "highscore" could never be updated, not even after signing in again. I have tried reloading the user but it doesn't do anything. (I am using the namespaced web version 8 in vanilla.js)
This is my code:
function gameOver () {
if (score > highscore) {
GAME_OVER_TEXT.innerText = 'New Highscore:';
HIGHSCORE.innerText = `${score} points.`;
STARS.classList.remove('hide');
SPARKLE.classList.remove('hide');
const user = firebase.auth().currentUser;
user.updateProfile({
highscore: score
}).then(() => {
console.log('Update successful');
}).catch((error) => {
console.log('Update unsuccessful' + error);
});
user.currentUser.reload();
} else {
GAME_OVER_TEXT.innerText = 'Your score:';
HIGHSCORE.innerText = `${score} points.`;
}
}
The call to reload immediately loads the current profile from the server. Since updateProfile is also an asynchronous call, you are now loading the un-updated profile. To fix this, you have to reload the profile after the update has completed. So:
user.updateProfile({
highscore: score
}).then(() => {
console.log('Update successful');
user.currentUser.reload().then(() => {
console.log('Profile reloaded');
});
}).catch((error) => {
console.log('Update unsuccessful' + error);
});
Note that updateProfile only accepts displayName and photoURL as properties, as you can't store other information in the user profile from the Firebase client-side SDKs. You can either use an Admin SDK (on a server or otherwise trusted environment) to set a custom claim with that value, or (more likely here) store the information in a custom database (such as Firestore or Realtime Database, which as also part of Firebase).
This has been covered quite a few times before, so I recommend checking out previous questions on the topic.