Chartjs-How to push Firestore data to ChartJS?

1👍

For each doc in the snapshot you are doing var myChart = new Chart(), creating a new chart each time.

You should build your data and labels arrays in the forEach and then (outside the forEach) create a new chart and pass it the arrays.

Something like the following (not tested):

var labelsArray = [];
var dataArray = [];

db.collection('Items').get().then((snapshot) => {
    snapshot.docs.forEach(doc => {
        var item = doc.data();

        var price = item.price;
        dataArray.push(price);

        var date = item.date;
        labelsArray.push(date);
    });
});

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
    labels: labelsArray,
    datasets: [{
        label: 'Items',
        data: dataArray ,  
    }]
},
options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    },
    // Container for pan options
    pan: {
        // Boolean to enable panning
        enabled: true,

        // Panning directions. 
        mode: 'x',

        speed: 1
    },

    // Container for zoom options
    zoom: {
        // enable zooming
        enabled: true,                      
        // Zooming directions. 
        mode: 'x',
        }
    }
});

Leave a comment