rank
rank

Reputation: 2544

Show length of data array in VueJS after getting the data from API

I'm using Vue JS to get some data from an API. I want to get the length of this array and log to console via a method.

But it always logs the value of "0" instead of the real length.

I can access the data in the html without any problem and show the length ( {{ termine.length }} ).

But I want to do it using the method "logToConsole".

It seems to be a problem to access the data (which seems to be undefined in the moment of function call).

I fetch the data on "created", and output the length in "mounted", so it should be available (?).

Do you have any idea why I cannot access the data of the array in my "mounted" function, even after getting the data in "created"?

new Vue ({
    el: "#calendar",
    data: {
        termine: [],
    },
},
created() {
    fetch("https://www.myurl.com/data/?json&function=GetEvents")
        .then(response => response.json())
        .then((data) => {
            this.termine = data;
        })
},
mounted() {
    this.logToConsole();
},
methods: {
    logToConsole: function () {
        console.log(this.termine.length);
    },
},

})

Upvotes: 0

Views: 706

Answers (1)

plsdev89
plsdev89

Reputation: 732

Of course, created hook is triggered before mounted. But you know, you are setting termine property using API response and it is happen with async. If you simple set termine property with simple statement like this.termine = ['a', 'b'], it will logs 2.

If you want log the data after getting the value using API, you could use watch. like:

watch: {
   termine(val) {
      console.log(val)
   }
}

Upvotes: 3

Related Questions