Trying to wrap my head around the composition api, but apparently need a bit of help. Loading in all my "Quotes" from a Firebase DB with this
import { ref } from 'vue'
import { projectFirestore } from '../firebase/config'
const getQuotes = () => {
const quotes = ref([])
const error = ref(null)
const load = async () => {
try {
const res = await projectFirestore.collection('quotes').get()
quotes.value = res.docs.map(doc => {
return { ...doc.data(), id: doc.id }
})
}
catch (err) {
error.value = err.message
console.log(error.value)
}
}
return { quotes, error, load}
}
export default getQuotes
Which works as intended. But then I try to create a filter so only 1 Quote is shown randomly like this:
<template>
<section class="home">
<h1 style="color: pink">{{ randomQuote }}</h1>
<Quote :quote="quote" v-for="quote in quotes" :key="quote.id" />
</section>
</template>
<script>
import getQuotes from '@/composables/getQuotes'
import Quote from '@/components/Quote.vue'
import { computed } from '@vue/reactivity'
export default {
name: 'Home',
components: { Quote },
setup() {
const { quotes, error, load } = getQuotes()
const randomQuote = computed(() => {
return quotes.Math.floor(Math.random() * quotes.length)
})
load()
return { randomQuote, quotes, error }
}
}
</script>
In my head this should work... anyone who can spot the error and give me a heads up?
This syntax means quotes.Math.floor(Math.random() * quotes.length) that a property named Math on quotes array, while it's Math global variable that is supposed to be accessed. Since an array doesn't have such property, this will result in error. If the intention is to specify dynamic array index, it cannot be differed from accessing a property.
In order to access an index, bracket notation should be used, likely:
quotes[Math.floor(Math.random() * quotes.length)]