Search code examples
javascriptfirebasevue.jsfirebase-realtime-databasevue-cli-3

Reading data with firebase and vue.js


I'm not very experienced, and I was wondering how I can extract data from firebase, updating the status element of vue.js. The problem is that I can not extract the fusion data dedicated to firebase "snapshot". I leave you all the code and all the errors below.

Vue.js code:

<template>
  <div id="app">

      <div>
        <h1>ON/OFF led</h1>
        <h2>Status: {{ device.status() }}</h2>
      </div>


  </div>
</template>

<script>
import Vue from 'vue'

import { deviceStatusRef } from './firebase';

var pinReport;


export default {
  data () {
    return {
      name: '',
      device: {
        nome: 'led',
        status: function(){
              deviceStatusRef.on("value", function(snapshot) {
                pinReport = snapshot.val();
                console.log("[1] - pinReport value --> " + pinReport);
              });
              console.log("[2] - pinReport VALUE --> " + pinReport);
              return pinReport;
            }
      }
    }
  },

}
</script>

<style>

</style>

Errors on Chrome:

enter image description here


Solution

  • That's the expected behavior. Data is loaded from Firebase asynchronously. By the time your [2] log statement runs, the data hasn't been loaded yet and pinReport is undefined.

    This means that all code that needs the data must be inside the callback, like your [1] log statement. It also means that you can't return the value from the database from a function, since the return runs before the data is loaded.