I am trying to sync my chart' array data with my firebase value. Chart getting arrays for label and data. I would like to bind this Chart data value to my firebase object. Here is normal chart creation with hard coded static values:
data()
{
return {appChart: {data: {labels: ["A"], series: [[3]]}},}
},
Now, I would like to bind this value (3) with my firebase object.. Normally I can use firebase object like this with no problem:
new Vue({
data: () => ({ myObjA: null }),
firebase: {
myObjA: db.ref('myObjA'),
asObject:true
},
})
But I cant bind and dynamic update this myObjA with Chart array series ‘a’ like;
data()
{
return {appChart: {data: {labels: ["A"], series: [[myObjA]]}},}
},
How can I do that ?
You can change appChart to be computed properties:
export default {
data: () => ({ myObjA: null }),
firebase: {
myObjA: db.ref('myObjA'),
asObject:true
},
computed: {
appChart() {
return {
data: {
labels: ["A"],
series: [[this.myObjA]]
}
}
}
}
}
</script>
Related
I have a Nuxt component that loads a chart using chart.js, filled with data from a Firestore database. The data points are loading as a flat line at the bottom of my chart. However, the data has different value ranges when hovered.
How do I get the data points to render in the correct locations to produce an actual graph?
I've tried using a loaded variable to load the chart after the Firestore data is retrieved. I end up with the exact same issue.
I've tried adding some static weight array data before the data is pushed to it. When doing that, it showed those points accurately, but the rest laid flat on the bottom (still showing valid data point values on hover).
<template>
<div id="container">
<canvas ref="chart"></canvas>
</div>
</template>
<script>
import { firebase, db } from '#/plugins/firebase'
import Chart from 'chart.js'
const color = ['#3AC', '#D91D63', '#5F6982', '#F4B651', '#3F4952']
export default {
data() {
return {
laoded: false,
weightData: [],
}
},
async mounted() {
// retrieve weight data from firebase
this.getWeightData()
const ctx = this.$refs.chart
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
data: this.weightData,
backgroundColor: color[0],
borderColor: color[0],
borderWidth: 1,
fill: false,
label: 'weight',
responsive: true
}]
},
options: {
legend: {
usePointStyle: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 10
}
}]
},
tooltips: {
callbacks: {
afterBody(tooltip, dataset) {
let data = 'goal: goal here'
return data
}
}
}
}
})
},
methods: {
getWeightData() {
firebase.auth().onAuthStateChanged(async user => {
if (user) {
const data = await db.collection('users').doc(user.uid).collection('weight').get()
.then(querySnapshot => {
if (!querySnapshot.empty) {
querySnapshot.forEach(doc => {
this.weightData.push(doc.data().weight)
})
}
})
}
})
this.loaded = true
}
}
}
</script>
I expect a line graph with the data points from the weightData array. All I'm getting is a flat line with different values in the tooltips.
Also, the chart's range is 0 to 1, even though weightData values go up as far as 200.
getWeightData() populates weightData asynchronously, so you'd have to await the function call before proceeding with setting up the chart.
First, wrap getWeightData() in a Promise 1️⃣so that you could return the fetched weight data 2️⃣(instead of setting this.weightData inside the Promise):
methods: {
getWeightData() {
return new Promise((resolve, reject) => { /* 1 */
firebase.auth().onAuthStateChanged(user => {
if (user) {
db.collection('users')
.doc(user.uid)
.collection('weight')
.get()
.then(querySnapshot => {
const weightData = []
if (!querySnapshot.empty) {
querySnapshot.forEach(doc => {
weightData.push(doc.data().weight)
})
}
resolve(weightData) /* 2 */
})
.catch(reject)
} else {
reject()
}
})
})
}
}
Then in mounted(), store the awaited result of getWeightData() in this.weightData 3️⃣:
async mounted() {
this.weightData = await this.getWeightData() /* 3 */
/* now, setup chart with `this.weightData` */
}
Im new in Vuejs. I started a project with Vue, Firebase and using Chart Js inside of it. Here is the details of problem.
If I give any value of sales_today in data() it shows properly on mounted where I use it by this.sales_today also works perfectly in template {{sales_today}}.
But into the Created I'm trying to change this.sales_today value by an output of firebase query. then the output shows perfectly into template {{sales_today}} but not working inside the mounted here
**data: [this.sales_today,30,60,10]**
Template
<template>
{{sales_today}}
</template>
Data
data(){
return{
sales_today:''
}
},
Mounted
mounted() {
data: {
datasets: [{
data: [this.sales_today,30,60,10],
}]
}
}
Created
created(){
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total
})
}
Here is the complete code
https://github.com/Shakilzaman87/pukucrm/blob/master/src/components/dashboard/Dashboard.vue
This should be on mounted(). I don't have the editor on comments and i will answer here.
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total;
var chart = this.$refs.chart;
var ctx = chart.getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:this.labels,
datasets: [{
label: 'Sales of June',
data: [this.sales_today,30,60,10],
backgroundColor: [
'#ffffff'
],
borderColor: [
'#1976d2'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
});
})
P.S. check the console for errors
I'm running into the same problem as issue #53 of aldeed:tabular. When defining the table as suggested in the documentation, it is too soon to invoke a translation function (TAPi18n.__ or other), since the I18N variables are not yet set.
What is the nice, reactive way of feeding the translated column titles into DataTables, either directly as suggested by aldeed himself upon closing the issue, or through aldeed:tabular?
With .tabular.options
There is a way with the template's .tabular.options reactive
variable, but it is quirky. Here is a variation of the library
example using
tap-i18n to translate the
column headers:
function __(key) {
if (Meteor.isServer) {
return key;
} else {
return TAPi18n.__(key);
}
}
Books = new Meteor.Collection("Books");
TabularTables = {};
TabularTables.Books = new Tabular.Table({
name: "Books",
collection: Books,
columns: [] // Initially empty, reactively updated below
});
var getTranslatedColumns = function() {
return [
{data: "title", title: __("Title")},
{data: "author", title: __("Author")},
{data: "copies", title: __("Copies Available")},
{
data: "lastCheckedOut",
title: __("Last Checkout"),
render: function (val, type, doc) {
if (val instanceof Date) {
return moment(val).calendar();
} else {
return "Never";
}
}
},
{data: "summary", title: __("Summary")},
{
tmpl: Meteor.isClient && Template.bookCheckOutCell
}
];
}
if (Meteor.isClient) {
Template.tabular.onRendered(function() {
var self = this;
self.autorun(function() {
var options = _.clone(self.tabular.options.get());
options.columns = getTranslatedColumns();
self.tabular.options.set(_.clone(options));
});
});
}
With a forked version
I created a pull request against branch devel of meteor-tabular to enable the straightforward, reactive-based approach like so:
<template name="MyTemplateWithATable">
{{> tabular table=makeTable class="table table-editable table-striped table-bordered table-condensed"}}
</template>
var MyColumns = ["title", "author"];
// Assume translations are set up for "MyTable.column.title", "MyTable.column.author"
// in other source files; see TAPi18n documentation for how to do that
function makeTable() {
return new Tabular.Table({
name: "MyTable",
collection: MyCollection,
columns: _.map(MyColumns,
function(colSymbol) {
return {
data: colSymbol,
title: TAPi18n.__("MyTable.column." + colSymbol)
};
})
});
}
if (Meteor.isServer) {
// Called only once
makeTable();
} else if (Meteor.isClient) {
// Reactively called multiple times e.g. when switching languages
Template.MyTemplateWithATable.helpers({makeTable: makeTable});
}
Recent versions of aldeed:tabular allow to specify a function for setting the column titles.
import {TAPi18n} from 'meteor/tap:i18n';
TabularTables = {};
TabularTables.Departments= new Tabular.Table({
name: 'Departments',
collection: Departments,
responsive: true,
autoWidth: true,
stateSave: false,
columns: [
{data: "name", titleFn: function() {
return TAPi18n.__("name");
}},
{data: "description", titleFn: function() {
return TAPi18n.__("description");
}}
]
});
The language change is reactive. If you have translations you can switch and columns will be translated.
TAPi18n.setLanguage("en");
TAPi18n.setLanguage("de");
Word of warning:
This currently does not work when you include invisible columns in your table data. The offset is wrong and you get wrong column titles.
I am creating an application using Meteor and ReactJS. I have a collection which I subscribe to and the client side, and I want to render a ChartJS Polar Area chart based on the data from the collection.
The problem is that whenever I update the collection, both the new data and the old data appears on the chart (when I hover, I get two different values for the segments, the old data and the new data).
Here is my code:
ChartComponent = React.createClass({
mixins: [ReactMeteorData],
getMeteordata() {
let data = Meteor.subscribe("sentiment");
return {
chartData: [
{
value: MyCollection.find({"item": "test1"}).count(),
color: "green",
label: "Test1"
},
{
value: MyCollection.find({"item": "test2"}).count(),
color: "yellow",
label: "Test2"
},
{
value: MyCollection.find({"item": "test3"}).count(),
color: "red",
label: "Test3"
}
]
}
},
_drawGraph() {
let ctx = document.getElementById("my-canvas").getContext("2d");
let polarChart = new Chart(ctx).Polararea(this.data.chartData, {
animateScale: true,
});
return polarChart;
},
componentDidMount() {
this._drawGraph();
},
componentDidUpdate() {
this._drawGraph().update();
},
render() {
return <canvas id="my-canvas"></canvas>
}
});
Help would be appreciated. Thank you very much!
Note:
I am using react version 0.14. The official react-chartjs component does not work, due to some of the api changes.
I have the following:
require([
"dojo/dom",
"dojo/on",
"dojo/store/Observable",
"dojo/store/JsonRest",
"dojo/store/Memory",
"dgrid/OnDemandGrid"
], function (dom, on, Observable, JsonRest, Memory, OnDemandGrid) {
var store = new JsonRest({
target: 'client/list',
idProperty: 'id'
});
var grid = new OnDemandGrid({
columns: {
"id": "ID",
"number": "Name",
"description": "Description"
},
sort: "lastName",
store: store
}, "grid");
});
client/list is a rest url returning a json object {data:[...]}, but the content of the list never shows up :/
I think the problem is caused by the async data loading, because with a json hard coded object the content show up
EDIT :
I've succeeded in achieving this by using a dojo/request, but the JsonRest shouldn't normally act the same way ? Can someone point me to the right direction ?
require([
'dojo/dom',
'dojo/on',
'dojo/store/Memory',
'dojo/request',
'dgrid/OnDemandGrid'
], function (dom, on, Memory, request, OnDemandGrid) {
request('client/list', {
handleAs: 'json'
}).then(function (response) {
// Once the response is received, build an in-memory store with the data
var store = new Memory({ data: response });
// Create an instance of OnDemandGrid referencing the store
var grid = new OnDemandGrid({
store: store,
sort: 'id', // Initialize sort on id, ascending
columns: {
'id': 'ID',
'number': 'Name',
'description': 'Description'
}
}, 'grid');
console.log(store);
on(dom.byId('queryForm'), 'input', function (event) {
event.preventDefault();
grid.set('query', {
// Pass a RegExp to Memory's SimpleQueryEngine
// Note: this code does not go out of its way to escape
// characters that have special meaning in RegExps
description: new RegExp(this.elements.last.value, 'i')
});
});
on(dom.byId('queryForm'), 'reset', function () {
// Reset the query when the form is reset
grid.set('query', {});
});
});
});
Ok problem found :/
My "client/list" url was returning a json object like this:
{data: [{id:"1", label: "test"}, {id:"2", label: "test"}]}
Turns out that the JsonRest object is already encapsulating data in a data node, so by returning a json like this:
{[{id:"1", label: "test"}, {id:"2", label: "test"}]}
everything worked fine :)