VueJS array returns length = 0

Sjobi

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));               

                });
            },
    });
Terry

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://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related