Tashi Tobgay
Tashi Tobgay

Reputation: 191

VueJS: Uncaught (in promise) TypeError: Cannot read property 'push' of undefined

I am getting the 'cannot read property push of undefined' error: here is my vueJs code:

data:{
CoIsignedListUID:[]
}
methods:{

fetchCoISigned: function () {
            this.$http.get('/cimsm/public/api/fetchCoIsigned/' + this.conflictofInterest.complaintID).then(function (response) {
                var data = response.data;
                this.$set('CoIsignedList', data);
                data.forEach(function (detail) {
                    this.CoIsignedListUID.push(detail.uID);
                });
            });

what am i doing wrong? Thanks

Upvotes: 7

Views: 26006

Answers (2)

gurghet
gurghet

Reputation: 7706

this.CoIsignedListUID is not defined

probably because this is not the this you think it is

you should do

var _this = this

outside the function and then

_this.CoIsignedListUID.push(detail.uID);

Alternatively, you can use ES2015 arrow syntax.

Instead of:

.then(function (response) {}

Use:

.then((response) => {}

The 'this' is now available inside the function so no need for creating a new variable. Full details Here.

Upvotes: 12

kangbin
kangbin

Reputation: 1

this in the forEach callback is not the vue.js this. you can do this to solve this problem.

this.$http.get("...").then(function(response){
    var data = response.data;
    this.$set('CoIsignedList', data);
    var that = this;
    data.forEach(function (detail) {
        that.CoIsignedListUID.push(detail.uID);
    });
});

Upvotes: 0

Related Questions