I have a script with a load()
function that connects to a Firestore database, retrieves a collection and stores it in 'moods' variable. The try-catch block are from a tutorial I'm following, and it's working.
Then I'm trying to convert the moods object I'm getting to an array that contains only one specific value for each 'mood', namely a rating (1-10).
import { ref } from "vue";
import { projectFirestore } from '../firebase/config'
const moods = ref([])
const error = ref(null)
const ratings = ref([])
const load = async () => {
try {
const res = await projectFirestore.collection('moods')
.orderBy('timestamp', 'desc')
.get()
moods.value = res.docs.map(doc => {
return {
...doc.data(),
id: doc.id
}
})
} catch (err) {
error.value = err.message
console.log(error.value);
}
const moods_length = Object.keys(moods.value).length
for (let i = 0; i < moods_length; i++) {
ratings.value.push(moods.value[i].rate_feeling)
}
const ratings_array = Object.values(ratings.value)
console.log(ratings_array);
return ratings_array
}
export default load
I'm new to javascript, so this part might not be optimal, but it's working. When I run load() from my Composition API in my view, I get this in the console:
Array(10) [ 5, 9, 3, "7", "6", "2", "7", "2", "9", "1" ]
Exactly what I need (my goal is to plot these values on a graph afterwards - and don't mind the fact that not all values are integers here).
Now, I would like to be able to retrieve this array (ratings_array) in my view. I'm trying something like this, but to no avail:
<template>
<div class="container">
<h2>Stats </h2>
<div class="line-chart">
<line-chart
:legend="true"
label="Average mood rating"
:data="my_array"
></line-chart>
</div>
<!-- <div v-for="mood in data_array">{{ mood.five_emotions }}</div> -->
</div>
</template>
<script>
import { ref } from '@vue/reactivity'
import load from '../composables/stats2'
export default {
setup() {
const my_array = load()
return { my_array, load }
}
}
</script>
But if I console.log my_array, it logs this object:
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(10) [ 5, 9, 3, … ]
<prototype>: Promise.prototype { … }
I have been fiddling with this for hours and just can't figure out how to do this.
Thanks for any feedback!