Reputation: 453
I'm trying to get vuefire/vue/firebase to work when there is auth and separate users. I can get it to work when I pass a UID manually...
let booksRef = db.ref('Users/' + 'SOhUKhcWzVRZmqe3AfcWMRwQR4r2' + '/Books');
But, when I try and replace the hard coded uid with one that comes from Firebase, I get a null result... It is basically not ready at the time of the call, even if the user is logged in...:
beforeCreate: function() {
var context = this;
Firebase.auth().onAuthStateChanged(function(user) {
if (user) {
currentUser = user;
context.currentUserId = user.uid;
context.currentUserEmail = user.email;
context.signedIn = true;
}
else {
context.currentUserId = null;
context.currentUserEmail = null; }
});
How can I ensure I get the UID first before I create the path to the dataset?
Thanks!
Upvotes: 1
Views: 478
Reputation: 453
I figured this out, with the help of a GitHub example.
I'm providing the GitHub link below. But, in short, you have to do things a bit differently when using auth and UID... It's not well documented by Vuefire. You need to use a VueJS lifecycle method beforeCreate, along with a special Vuefire binding $bindAsArray.
Here's a snippet that shows the usage:
new Vue({
el: '#app',
beforeCreate: function() {
// Setup Firebase onAuthStateChanged handler
//
// https://firebase.google.com/docs/reference/js/firebase.auth.Auth
// https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.user = user
// https://github.com/vuejs/vuefire/blob/master/src/vuefire.js#L169
this.$bindAsArray('messages', db.ref('messages/' + user.uid))
} else {
// https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInAnonymously
firebase.auth().signInAnonymously().catch(console.error)
}
}.bind(this))
},
// Initialize reactive props, bind later when user is available
data: {
user: {},
messages: []
},
See the full github example here:
Upvotes: 2