Home > Back-end >  Vue cannot read property of undefined for attribute of object but only in template
Vue cannot read property of undefined for attribute of object but only in template

Time:12-14

I have a variable created in vue with

    data() {
        return {
            plans: [],
}

Plans is later given objects pushed to it. When I print that object in the js it gives {id: 'filler', name: 'Premium', priceId: 'filler', price: '10000'}. I can also get the name specifically with console.log(this.plans[1]['name']) and it will give 'Premium' correctly. However, in the template I'm trying to display the name with <h1>{{plans[0].name}}</h1> (I also tried as ['name']) and it says Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name'). However, if I just give it <h1>{{plans[0]}}</h1> it shows the entire object correctly. Very confused what I'm missing, please let me know if any more info is needed.

EDIT: the array is populated with the following

    async getPlans(){
        
        const db = getFirestore()
        const productsRef = collection(db, "products")
        const productsQuery = query(productsRef, where("active","==", true))
        const productsQuerySnap = await getDocs(productsQuery)
        // console.log(productsQuerySnap[0])
        // const temp = []
        for (let i = 0; i<2; i  ){
            // const doc = i.docs
            console.log(productsQuerySnap.docs[i])
            const pricesRef = collection(db, "products", productsQuerySnap.docs[i].id, "prices")
            const pricesQuerySnap = await getDocs(pricesRef)
            const name = productsQuerySnap.docs[i]["_document"]["data"]["value"]["mapValue"]["fields"]["name"]["stringValue"]
            console.log(pricesQuerySnap.docs[0]["id"])
            const priceId = pricesQuerySnap.docs[0]["id"]
            const price = pricesQuerySnap.docs[0]["_document"]["data"]["value"]["mapValue"]["fields"]["unit_amount"]['integerValue']
            console.log({id: productsQuerySnap.docs[i].id, name: name, priceId: priceId, price: price})
            this.plans.push({id: productsQuerySnap.docs[i].id, name: name, priceId: priceId, price: price})
        }
        console.log(this.plans[0]['name'], "plans is running")
    

  },

it was run in mounted

CodePudding user response:

 data() {
        return {
            plans: Object,
}

CodePudding user response:

I'm unsure if there is a solution utilizing methods and mounted, but I got around the issue by using setup() rather than methods and mounted. I set the value of a ref to the full object array and then returned the value at the end of setup and everything was properly accessed in the template.

  • Related