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

                });
            },
    });

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

My bad..I already had this, but hadn't added it to my question. Updated the question now with the code. The result is still the same however even with the JSON.parse() :/
@Sjobi Can you create a minimal, concrete, and verifiable example? Can you share what result actually look like? I've tested your code and it seems to work fine.

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.