XxRoKeTfAcExX
XxRoKeTfAcExX

Reputation: 47

Vue.js error: TypeError: Cannot read properties of undefined

My knowledge of vue.js is limited but as far as i'm aware this should work, for some reason when I try to access my variable in the data property it can't find it.

enter image description here

data: function() {
    return {
        id: 0,
        clients: []
    }
},
methods: {
    getClientData(){
        fetch('/view-clients/' + this.id).then(function (response) {
            return response.text();
        }).then(function (data) {
            this.clients = JSON.parse(data);
            this.id = this.clients[clients.length - 1].id;
        }).catch(function (error) {
            console.log('Error: ' + error);
        });
    }
}

Upvotes: 4

Views: 20485

Answers (1)

J. Titus
J. Titus

Reputation: 9690

Function scope is most likely the culprit. Use arrow functions instead so this refers to the Vue component.

data() {
    return {
        id: 0,
        clients: []
    }
},
methods: {
    getClientData(){
        fetch('/view-clients/' + this.id).then((response) => response.text())
          .then((data) => {
            this.clients = JSON.parse(data);
            this.id = this.clients[this.clients.length - 1].id;
          }).catch((error) => {
            console.log('Error: ' + error);
          });
    }
}

Upvotes: 9

Related Questions