Why aren't my data points getting placed in the corresponding locations in my chart? - firebase

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` */
}

Related

How to do pagination based on the document position within a collection? (offset pagination)

I'm trying to do a pagination where the user can see each button's page number in the UI. I'm using Firestore and Buefy for this project.
My problem is that Firestore is returning wrong queries for this case. Sometimes (depending the page that the users clicks on) It works but sometimes don't (It returns the same data of the before page button).
It's really messy I don't understand what's going on. I'll show you the code:
Vue component: (pay attention on the onPageChange method)
<template>
<div>
<b-table
:data="displayData"
:columns="table.columns"
hoverable
scrollable
:loading="isLoading"
paginated
backend-pagination
:total="table.total"
:per-page="table.perPage"
#page-change="onPageChange">
</b-table>
</div>
</template>
<script>
import { fetchBarriosWithLimit, getTotalDocumentBarrios, nextBarrios } from '../../../../firebase/firestore/Barrios/index.js'
import moment from 'moment'
const BARRIOS_PER_PAGE = 5
export default {
data() {
return {
table: {
data: [],
columns: [
{
field: 'name',
label: 'Nombre'
},
{
field: 'dateAddedFormatted',
label: 'Fecha añadido'
},
{
field: 'totalStreets',
label: 'Total de calles'
}
],
perPage: BARRIOS_PER_PAGE,
total: 0
},
isLoading: false,
lastPageChange: 1
}
},
methods: {
onPageChange(pageNumber) {
// This is important. this method gets fired each time a user clicks a new page. I page number that the user clicks.
this.isLoading = true
if(pageNumber === 1) {
console.log('show first 5...')
return;
}
const totalPages = Math.ceil(this.table.total / this.table.perPage)
if(pageNumber === totalPages) {
console.log('show last 5...')
return;
}
/* Here a calculate the next starting point */
const startAfter = (pageNumber - 1) * this.table.perPage
nextBarrios(this.table.perPage, startAfter)
.then((querySnap) => {
this.table.data = []
this.buildBarrios(querySnap)
console.log('Start after: ', startAfter)
})
.catch((err) => {
console.err(err)
})
.finally(() => {
this.isLoading = false
})
},
buildBarrios(querySnap) {
querySnap.docs.forEach((docSnap) => {
this.table.data.push({
id: docSnap.id,
...docSnap.data(),
docSnapshot: docSnap
})
});
}
},
computed: {
displayData() {
let data = []
this.table.data.map((barrioBuieldedObj) => {
barrioBuieldedObj.dateAddedFormatted = moment(Number(barrioBuieldedObj.dateAdded)).format("DD/MM/YYYY")
barrioBuieldedObj.totalStreets ? true : barrioBuieldedObj.totalStreets = 0;
data.push(barrioBuieldedObj)
});
return data;
}
},
mounted() {
// obtener primer paginacion y total de documentos.
this.isLoading = true
getTotalDocumentBarrios()
.then((docSnap) => {
if(!docSnap.exists || !docSnap.data().totalBarrios) {
// mostrar mensaje que no hay barrios...
console.log('No hay barrios agregados...')
this.table.total = 0
return;
}
const totalBarrios = docSnap.data().totalBarrios
this.table.total = totalBarrios
if(totalBarrios <= BARRIOS_PER_PAGE) {
return fetchBarriosWithLimit(totalBarrios)
} else {
return fetchBarriosWithLimit(BARRIOS_PER_PAGE)
}
})
.then((querySnap) => {
if(querySnap.empty) {
// ningun doc. mostrar mensaje q no hay barrios agregados...
return;
}
this.buildBarrios(querySnap)
})
.catch((err) => {
console.error(err)
})
.finally(() => {
this.isLoading = false
})
}
}
</script>
<style lang="scss" scoped>
</style>
The nextBarrios function:
function nextBarrios(limitNum, startAtNum) {
const query = db.collection('Barrios')
.orderBy('dateAdded')
.startAfter(startAtNum)
.limit(limitNum)
return query.get()
}
db is the result object of calling firebase.firestore(). Can I tell a query to start at a certain number where number is the index position of the document within a collection? If not, How could I approach this problem?
Thank you!
Firestore doesn't support offset or index based pagination. It's also not possible to tell how many documents the entire query would return without actually reading them all. So, unfortunately, what you're trying to do isn't possible with Firestore.
It seems also that you're misunderstanding how the pagination APIs actually work. startAfter doesn't take an index - it takes either a DocumentSnapshot of the last document in the prior page, or a value of the ordered field that you used to sort the query, again, the last value you saw in the prior page. You are basically going to use the API to tell it where to start in the next page of results based on what you found in the last page. That's what the documentation means when it says you are working with a "query cursor".

Vuefire with Chart on Vue.js

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>

Vuejs data not showing properly on mounted

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

How do i convert a single json record retrieved from firebase into an array

I am trying to take a single record from firebase to use in vuejs but I cant find out how to convert it to an array, if thats even what i should be doing.
my mutation
GET_CASE(state, caseId) {
state.caseId = caseId;
},
My action
getCase ({ commit, context }, data) {
return axios.get('http' + data + '.json')
.then(res => {
const convertcase = []
convertcase.push({ data: res.data })
//result below of what is returned from the res.data
console.log(convertcase)
// commit('GET_CASE', convertcase)
})
.catch(e => context.error(e));
},
I now get the following returned to {{ myCase }}
[ { "data": { case_name: "Broken laptop", case_status: "live", case_summary: "This is some summary content", contact: "", createdBy: "Paul", createdDate: "2018-06-21T15:20:22.932Z", assessor: "Gould", updates: "" } } ]
when all i want to display is Broken Laptop
Thanks
Example let obj = {a: 1, b: 'a'); let arr = Object.values(obj) // arr = [1, 'a']
async getCase ({ commit, context }, url) {
try {
let { data } = await axios.get(`http${url}.json`)
commit('myMutation', Object.values(data))
} catch (error) {
context.error(error)
}
}
But as I'm reading your post again, I think you don't want array from object. You want array with one object. So, maybe this is what you want:
async getCase ({ commit, context }, url) {
try {
let { data } = await axios.get(`http${url}.json`)
commit('myMutation', [data])
} catch (error) {
context.error(error)
}
}
Put this inside / after your .then
Object.keys(data).forEach(function(k, i) {
console.log(k, i);
});
With a response from Axios, you can get your data as:
res.data.case_name
res.data.case_number
....
Just build JavaScript object holding these properties and pass this object to your mutation. I think it is better than using an array.
const obj = {};
Object.assign(obj, res.data);
commit('GET_CASE', obj)
And in your mutation you do as follows:
mutations: {
GET_CASE (state, payload) {
for (var k in payload) {
if (payload.hasOwnProperty(k)) {
state[k] = payload[k]
}
}
}
}
Alternatively you can code your store as follows:
state: {
case: {},
...
},
getters: {
getCase: state => {
return state.case
},
....
},
mutations: {
GET_CASE (state, payload) {
state.case = payload
}
}
and you call the value of a case field form a component as follows:
const case = this.$store.getters.getCase
..... = case.case_name

Vuefire get Firebase Image Url

I am storing relative paths to images in my firebase database for each item I wish to display. I am having trouble getting the images to appear on the screen, as I need to get the images asynchronously. The firebase schema is currently as follows:
{
items: {
<id#1>: {
image_loc: ...,
},
<id#2>: {
image_loc: ...,
},
}
}
I would like to display each of these images on my page with code such as:
<div v-for="item in items">
<img v-bind:src="item.image_loc">
</div>
This does not work, as my relative location points to a place in firebase storage. The relavent code to get the true url from this relative url is:
firebase.storage().ref('items').child(<the_image_loc>).getDownloadURL()
which returns a promise with the true url. Here is my current vue.js code:
var vue = new Vue({
el: '.barba-container',
data: {
items: []
},
firebase: function() {
return {
items: firebase.database().ref().child('items'),
};
}
});
I have tried using computed properties, including the use of vue-async-computed, but these solutions do not seem to work as I cannot pass in parameters.
Basically, how do I display a list of elements where each element needs the result of a promise?
I was able to solve this by using the asyncComputed library for vue.js and by making a promise to download all images at once, instead of trying to do so individually.
/**
* Returns a promise that resolves when an item has all async properties set
*/
function VotingItem(item) {
var promise = new Promise(function(resolve, reject) {
item.short_description = item.description.slice(0, 140).concat('...');
if (item.image_loc === undefined) {
resolve(item);
}
firebase.storage().ref("items").child(item.image_loc).getDownloadURL()
.then(function(url) {
item.image_url = url;
resolve(item);
})
.catch(function(error) {
item.image_url = "https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
resolve(item);
});
});
return promise;
}
var vue = new Vue({
el: '.barba-container',
data: {
items: [],
is_loading: false
},
firebase: function() {
return {
items: firebase.database().ref().child('items'),
};
},
asyncComputed: {
processedItems: {
get: function() {
var promises = this.items.map(VotingItem);
return Promise.all(promises);
},
default: []
}
}
});
Lastly, I needed to use: v-for="item in processedItems" in my template to render the items with image urls attached
I was able to solve it without any extra dependencies not adding elements to the array until the url is resolved:
in my template:
<div v-for="foo in foos" :key="foo.bar">
<img :src="foo.src" :alt="foo.anotherbar">
...
</div>
in my component (for example inside mounted())
const db = firebase.firestore()
const storage = firebase.storage().ref()
const _this = this
db.collection('foos').get().then((querySnapshot) => {
const foos = []
querySnapshot.forEach((doc) => {
foos.push(doc.data())
})
return Promise.all(foos.map(foo => {
return storage.child(foo.imagePath).getDownloadURL().then(url => {
foo.src = url
_this.foos.push(foo)
})
}))
}).then(() => {
console.log('all loaded')
})

Resources