Hi,
I have had a good hard search around and have managed to create a chart using chartjs and looking up the data from my mongo collection. But it won’t update when I add another item to that collection. The examples I have seen all seem to do this differently and none of them are working for me. I have thrown the same question up on reddit but the community seems a bit more active here so hoping for a response.
I think the issue is in the Tracker.autorun() it doesn’t fire after I add more data.
Code below
Publish
if (Meteor.isServer) {
Meteor.publish("alerts", function alertsPublication() {
return Alerts.find();
});
}
Template
<template name = "dashboardChart" >
<canvas id = "dashboardChart" height = "125" > </canvas >
</template >
JavaScript
import {Template} from 'meteor/templating';
import {Chart} from 'chart.js/src/chart.js';
import {Alerts} from '../../api/alerts.js';
import './dashboardChart.html';
Template.dashboardChart.onCreated(function () {
});
Template.dashboardChart.onRendered(function () {
const alerts = this.subscribe("alerts");
Tracker.autorun(function () {
if (alerts.ready()) {
const datalabels = [];
const datavalues = [];
const now = new Date();
const lookupStartDate = new Date();
lookupStartDate.setMonth(lookupStartDate.getMonth() - 1);
lookupStartDate.setHours(0, 0, 0, 0);
const lookupEndDate = new Date();
lookupEndDate.setMonth(lookupEndDate.getMonth() - 1);
lookupEndDate.setHours(24, 0, 0, 0);
while (lookupStartDate < now) {
datalabels.push(moment(lookupStartDate).format('ddd Do MMM'));
datavalues.push(
Alerts.find({
createdAt: {
$gte: lookupStartDate,
$lte: lookupEndDate,
},
}).count()
);
lookupStartDate.setDate(lookupStartDate.getDate() + 1);
lookupEndDate.setDate(lookupEndDate.getDate() + 1);
}
const ctx = document.getElementById("dashboardChart");
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: datalabels,
datasets: [{
label: 'Alerts',
data: datavalues,
fill: false,
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255,99,132,1)',
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false,
labelString: 'Date'
}
}],
yAxes: [{
display: true,
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Number of Alerts'
}
}]
}
}
});
}
});
});