Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document.
For example,
The desired value is:
abc1 (displayName of the first array)
I attempted:
console log
0. documents (works, results below)
1. documents.value.displayName (error)
2. documents.value[0].displayName (error)
Uncaught (in promise) TypeError: Cannot read property '0' of null
at setup (Write.vue?125b:56)
but encountered failure.
How can I successfully retrieve values from refs arrays?
Log document
RefImpl {_shallow: false, __v_isRef: true, _rawValue: null, _value: null}
__v_isRef: true
_rawValue: Array(2)
0: {displayName: "abc1", orgName: "amazon", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53323232133232327d303034363e30">[email protected]</a>", regDate2: "2021-7-27", …}
1: {displayName: "abc2", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c3e3e3e1c3e3e3e73393d3f37">[email protected]</a>", orgName: "google", …}
setup Function
setup() {
const title = ref('')
const contents = ref('')
const { user } = getUser()
const userUid = user.value.uid
const { documents } = getCollection('user')
console.log(documents, 'documents log')
console.log(documents.value[0].displayName, 'documents value log')
return {title, contents, user, documents }
}
getCollection.js
const getCollection = (collection, query) => {
const documents = ref(null)
const error = ref(null)
// register the firestore collection reference
let collectionRef = projectFirestore.collection(collection)
if (query) {
collectionRef = collectionRef.where(...query)
}
const unsub = collectionRef.onSnapshot(snap => {
let results = []
snap.docs.forEach(doc => {
results.push({...doc.data()})
});
// update values
documents.value = results
error.value = null
}, err => {
console.log(err.message)
documents.value = null
error.value = 'could not fetch the data'
})
watchEffect((onInvalidate) => {
onInvalidate(() => unsub());
});
return { error, documents }
}
export default getCollection