scopeak
scopeak

Reputation: 545

How to output firebase database query into VueJs page

Currently I am querying a Firebase database for the current users username. I would like the value to display on the page inside the <template> area. Looked through the docs but still new to Vue.

Everything will output into the console correctly, I am just unsure of the next step to reference inside the <template> using moustache handles eg. {{ user.username }}

  data() {
    return {
      userName: ''
    }
  },
  methods: {
    getName: function() {
      var userId = firebase.auth().currentUser.uid;
      return firebase.database().ref('users/' +
        userId).on('value', function(snapshot) {
        if (snapshot.val()) {
          var obj = snapshot.val();
          var userName = snapshot.val().username;
          console.log('username:', userName)
        }
      });
    }
  }

Template

<template>
 <span>{{ user.username }} (Output result of var userName here)</span>
</template>

Upvotes: 0

Views: 1029

Answers (2)

acdcjunior
acdcjunior

Reputation: 135832

You are getting the username, but you are not updating the vue instance object (the data object). You can call vueInstance.$set(vueInstance, 'propertyName', newPropertyValue); to update it (more details here):

new Vue({
  el: '#app',
  data() {
    return {
      message: 'Hello Vue.js!',
      userName: ''
    }
  },
  methods: {
    getName: function() {
      var vueInstance = this;
      return setTimeout(function() {
        var userName = 'new username';
        vueInstance.$set(vueInstance, 'userName', userName);
        console.log('username:', userName)
      }, 2000);
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span>{{ message }}</span><br>
  <span>`{{ userName }}´ (Output result of var userName here)</span><br>
  <button @click="getName">Click me and wait for 2 seconds, the username will be updated</button>
</div>

Upvotes: 2

G. Santos
G. Santos

Reputation: 11

To you can use {{ user.username }}, in your data you need put like that:

data(){
    return{
        user: { 
            username:  ' '
        }
    }
}

and you are not updating the right username instance, you can change this line:

var userName = snapshot.val().username;

for this:

this.username = snapshot.val().username;

Upvotes: 1

Related Questions