0

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

})

1 Answer 1

3

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)
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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.