Array returns empty when I try to access through the mounted method

I’m learning Vue.js these days and I’m having a question. How do I access the data of a variable by mounted method? Currently my code looks like this:

export default {
    name: "StudentsComponent",
    data() {
        return {
            rows: [],
        };
    },
    methods: {
        loadStudents() {
            let vm = this;
            axios.get(`/studentlist`)
                .then(response => {
                    //Save students
                    vm.rows = response.data;
                    console.log(vm.rows); //Here I can see all the data loaded by the console
                })
                .catch(e => {
                    console.log('e');
                })
        },
    },
    mounted() {
        //I tried it that way and it didn't work.
        //let vm = this;
        //vm.loadStudents();
        //console.log(vm.rows);
        
        this.loadStudents();
        console.log(this.rows); //Here the array returns empty
    }
}

The console.log within the loadStudents method returns this:

The console.log within mounted returns this:
2

I also tried with await/async and also did not work. The code:

<script>
    export default {
        name: "StudentsComponent",
        data() {
            return {
                rows: [],
            };
        },
        methods: {
            loadStudents: async function() {
                let vm = this;
                const res = await fetch('/studentlist');
                vm.rows = await res.json();
            },
        },
        mounted() {
			this.loadStudents();
			console.log(this.rows); //Still returns empty
        }
    }
</script>

I appreciate any help, I’m done wracking my head with this.

axios performs asynchronous api call.
Obviously your other code will not wait for it.
And I will not recomment you to experiment with async/await since vue hooks are synchronous.

I’m curious and want to learn, could you elaborate?

This

But that’s not the same thing as in this case? He just want to wait til the data has been loaded, he doesn’t want to stop Vue from doing its things. I think the following would work without problem:

<script>
    export default {
        name: "StudentsComponent",
        data() {
            return {
                rows: [],
            };
        },
        methods: {
            loadStudents: async function() {
                let vm = this;
                const res = await fetch('/studentlist');
                vm.rows = await res.json();
            },
        },
        async mounted() {
		await this.loadStudents();
		console.log(this.rows); // Logs correct now.
        }
    }
</script>
1 Like

I think you are right. Thanks.