4

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);
        });
    }
}
4
  • 1
    Typo? Should be this.clients[this.clients.length - 1].id Commented Jan 9, 2022 at 22:27
  • 3
    Also, function scope applies here since you're not using arrow functions, so this isn't what you think it is. Commented Jan 9, 2022 at 22:29
  • Even with the above comments applied, if it is expected to “work” not depends on the parsed result returned. However, insufficient information has been provided as to what this really is. That is, this questions does not represent a complete minimal reproduction. Commented Jan 9, 2022 at 22:30
  • 1
    Use arrow functions, otherwise this in your callbacks do not refer to the Vue component instance. Also, clients is undefined: do you mean this.clients[this.clients.length - 1].id instead? Commented Jan 9, 2022 at 22:34

1 Answer 1

9

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);
          });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.