Search code examples
ajaxvue.jsxmlhttprequest

How to pass the XMLHttpRequest responseText in a Vue properties


I would like to be able to retrieve the response of my request and to be able to store it in a property, but I can't reach my property customerArray in the function onreafystatchange.

export default {
        name: "CustomerList",
        data() {
            return {
                customerArray: []
            }
        },
        methods: {
            retrieveAllCustomer: function () {
                var xhr = new XMLHttpRequest();
                var url = "https://url";
                xhr.open("GET", url, false);
                xhr.onreadystatechange = function () {
                    if (this.readyState === XMLHttpRequest.DONE) {
                        if (this.status === 200) {
                            //Does not refer to customerArray
                            this.customerArray = JSON.parse(this.responseText);
                        } else {
                            console.log(this.status, this.statusText);
                        }
                    }
                };
                xhr.send();
            }
        }
    }

Is it possible to point to customerArray inside onreadystatechange?


Solution

  • xhr.onreadystatechange = function () causes the this reference to change to the XMLHttpRequest object. Consequently, this.customerArray does not exist anymore. In order to circumvent that, create a new reference to the original this:

    retrieveAllCustomer: function () {
        var comp = this;
        var xhr = new XMLHttpRequest();
                var url = "https://url";
                xhr.open("GET", url, false);
                xhr.onreadystatechange = function () {
                    if (this.readyState === XMLHttpRequest.DONE) {
                        if (this.status === 200) {
                            comp.customerArray = JSON.parse(this.responseText);
                        } else {
                            console.log(this.status, this.statusText);
                        }
                    }
                };
                xhr.send();
            }