0

I'm trying to store data to a my usersRef in Firebase but it is being stored by the wrong key (userId).

After registering a new user, I give them a certain amount of credits.

addUser: function () { firebase.auth().createUserWithEmailAndPassword(this.newuser.email, this.newuser.password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); console.log("adding user"); try { var user = firebase.auth().currentUser; var userRef = database.ref('users/' + user.uid + '/'); userRef.set({'credits': this.newuser.credits}); if (user){ this.logInShow = false; } } catch(err){ } }, 

Elsewhere users can deploy offers, which should be stored to the same userID as the credits. However, a new userID is created and I am left with one userId that has a credits property and one that has an offer.

deployOffer: function(){ try { var user = firebase.auth().currentUser; var userOffersRef = database.ref('users/' + user.uid + '/offers'); offersRef.push(this.newoffer); userOffersRef.push(this.newoffer); this.offerShow = false; this.post = false; } catch (err){ console.log(err); } }, 

How could firebase.auth().currentUser.uid be returning different keys when I've only registered one? Here is what my db looks like after registering and then posting an offer:

enter image description here

1 Answer 1

2

You have a race condition in your code. Creating a user takes time, so is an asynchronous operation. But you are immediate writing the initial credits for the user, which means that you are actually writing them to the previously signed in user (overwriting their existing credits and offers in the process).

The solution is to write the initial credits in the completion listener of createUserWithEmailAndPassword:

addUser: function () { firebase.auth().createUserWithEmailAndPassword( this.newuser.email, this.newuser.password ).then(function(user) { console.log("adding user"); var userRef = database.ref('users/' + user.uid + '/'); userRef.set({'credits': this.newuser.credits}); if (user){ this.logInShow = false; } }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); }, 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.