2

I am using Vue.js with Chart.js in order to retrieve some data from Firebase and display it on a chart. This is my code:

import {Line} from 'vue-chartjs'

let Firebase = require('firebase');
//
let config = {
    apiKey: '****************************',
    authDomain: '****************************',
    databaseURL: '****************************',
    storageBucket: '****************************'
};

let firebaseApp = Firebase.initializeApp(config);
let db = firebaseApp.database();
let schools = db.ref('schools');

export default Line.extend({
    firebase: {
        schoolsArray: schools
    },
    data(){
        alert('data');
        return {
            names: []
        }
    },
    computed: {
        schoolNames: function () {
            for (let item of this.schoolsArray) {
                this.names.push(item.name);
            }
            alert('computed');
            return this.names
        }
    },

    mounted () {
        alert('mounted');
        this.renderChart({
            labels: this.names.toString(),
            datasets: [{
                label: 'School Reports', backgroundColor: '#dd4935',
                data: [10, 20, 50, 12, 34, 43, 45]
            }]
        }, {responsive: true, maintainAspectRatio: true})
    }
})

The problem is that the names array are always empty and the labels are not displayed. Here is how it looks: enter image description here

I need to display the school names on the x axis!

On the picture below is the Vue.js debugger results: enter image description here

1 Answer 1

2

db.ref('school') returns a 'firebase.database.Reference' object you have to retrieve the data from it. you could add this to your vue mounted lifecycle hook:

db.ref('school').once('value')
 .then((dataSnapshot) => {
   this.schoolsArray = dataSnapshot.val();
 });

you could also use the .on method which will automatically fire your callback each time when the data changes on the server. so make sure you remove that when the component is destroyed. for documentation see: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once

Sign up to request clarification or add additional context in comments.

3 Comments

I have posted one more picture which shows that the names are retrieved but are not shown on the graph!
does it help if you invoke your renderChart method in the .once callback again?
yes I use this code into the methods lifecycle hook and call it inside mounted before the renderChart but still I can't see any labels o my chart

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.