Alex Chen
Alex Chen

Reputation: 133

VueJS - Cannot read property 'status' of undefined

Although the output is correct. I have this error: Cannot read property 'status' of undefined. I suspect it is because listing is added after ajax call. How do I improve this?

<template v-for="status in showStatus">
    <div class="col-sm-1">{{status}}</div>
</template>

<script>
    var app = new Vue({
        el: "#app",
        data: { 
            listing: []
        },
        created: function(){
            axios.get('/getListing')
            .then(function (response) {
                app.listing = response.data;
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        computed: {
            showStatus(){
                return this.listing[0].status;
            }
        }
    });
</script>

Upvotes: 1

Views: 2134

Answers (1)

Phil
Phil

Reputation: 164766

As you've guessed, this is because listing starts as an empty array which is populated at a later time.

Your computed property doesn't do any checks for this and this.listing[0] will be undefined early on.

You just need to add a check to your computed poperty

computed: {
  showStatus () {
    return this.listing[0]?.status || []
  }
}

See Optional chaining (?.) if you haven't seen that syntax before.


An alternative would be to initialise listing with some safe default data

data: () => ({
  listing: [{ status: [] }]
})

Upvotes: 1

Related Questions