stacj aa
stacj aa

Reputation: 621

How to wait for data from a parent in a component method

I have an API call from a layout and I want to send an object with API data to my component.

Problem is, my object is empty as the method is called in the mounted() function. So, I need to execute this function only if I have data on my API service.

axios.get('/class')
    .then((response) => {
        console.log(response.data.results)
        response.data.results.forEach(element => {
            const object = {
                clientId: element.client.objectId,
                price: element.price || 0,
                driverId: element.objectId || null
            }
            this.serviceData.tripsInfo.push(object) // service data is the object will send to the the component
            ...

HTML :

<class title="List of class" :points="serviceData"/>

class component:

props: {
    points: {} // here is the layout data
},
mounted () {
    console.log(this.points)
    const reducer = (accumulator, currentValue) => accumulator + currentValue
    this.totalPrices = this.points.class.map(x => x.price).reduce(reducer) // here I got a problem (Reduce of empty array with no initial value")
},

Upvotes: 0

Views: 97

Answers (2)

Dan Knights
Dan Knights

Reputation: 8368

A watcher function will watch for whichever prop or data property has the same name and run the corresponding function each time its dependency updates.

props: {
    points: Object
},
watch: {
    points() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        this.totalPrices = this.points.class.map(x => x.price).reduce(reducer)
    }
}

So, essentially, as soon as points is populated with data, the reducer will run.

Alternatively, you can condense all of this down to a computed property:

computed: {
    totalPrices: function() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        return this.points.class.map(x => x.price).reduce(reducer)
    }
}

Upvotes: 1

stacj aa
stacj aa

Reputation: 621

Can use : V-if to solve this like:

<class title="" v-if="serviceData.class.length > 0" :points="serviceData"/> 

Upvotes: 0

Related Questions