Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 859
A. AZHA Avatar asked Oct 17 '25 09:10

A. AZHA


1 Answers

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();
        }
like image 142
SurfMan Avatar answered Oct 20 '25 16:10

SurfMan