Sjobi
Sjobi

Reputation: 7

VueJS array returns length = 0

I have created an array in my VueComponent.

When I run a console.log(myArray.length) it says "0", however if I run a console.log(myArray) it shows that the array has the expected data. Check the screenshot from console below. The first part shows myArray, the second is myArray.length (circled in red)

See screenshot

Here is my current code:

   Vue.component('invoice-archive', {
    data: function () {
                return {
    invoices: [],
      }
    },
    created() { 
       this.myUpdateMethod();
    },
    methods:{
      myUpdateMethod: function(){
          var $this = this;
          let data = { 'id': installationId };

          this.getAjax('myUrlHere', data).then(function (result) {  
            if(!result.length ) return; // <-- This was the problem
            $this.invoices.push(JSON.parse(result));
    console.log($this.invoices); // This shows the expected content of my array
console.log($this.invoices.length); // This shows 0
        }); 
      },
       getAjax(url, data, success) {

                return new Promise(function (resolve, reject) {

                    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

                    xhr.onload = function () {

                        resolve(this.responseText);
                    }

                    xhr.onerror = reject;

                    xhr.open('POST', url);

                    xhr.setRequestHeader('Content-Type', "application/json;charset=UTF-8");

                    xhr.send(JSON.stringify(data));               

                });
            },
    });

Upvotes: 0

Views: 1629

Answers (1)

Terry
Terry

Reputation: 66198

That is because when you are resolving the promise with this.responseText, you are passing a string into it. You will need to convert the response to JSON first, i.e.:

resolve(JSON.parse(this.responseText));

Since you're using VueJS, you might want to consider using axios instead of rolling your own AJAX request handler: https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

Upvotes: 2

Related Questions