Kopty
Kopty

Reputation: 548

Data doesn't show in console.log but renders fine in template

I have a Vue component in which I make an axois call to get all employees data, store it in an array, and display it in a table. That works just fine.

The behavior that I'm confused with however can be seen in the getEmployees() method below, where I have console.log(this.employees);

When I check the console, the object that is being returned there is blank and doesn't have any employees data, even though the same data object, when iterated through in the template, is displaying all the employees data.

Have a look at the code:

<template>
    <b-table striped hover :items="employees"></b-table>
</template>

<script>
    export default {
        data() {
            return {
                employees: []
            }
        },

        methods: {
            getEmployees() {
                axios.get('/api/employees')
                    .then(response => this.employees = response.data)

                console.log(this.employees);
            }
        },

        created() {
            this.getEmployees()
        }
    }
</script>

The reason I did console.log there was because I wanted to traverse that data and format all the salaries data within that array to a money format (i.e. comma after thousands, currency symbol, etc.)

Any ideas?

Thanks.

Upvotes: 0

Views: 112

Answers (1)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

Your scope for assigning values to this.employees is within promise's .then() method. Try expanding your arrow function and then within .then() method put the console.log() call.

<template>
    <b-table striped hover :items="employees"></b-table>
</template>

<script>
    export default {
        data() {
            return {
                employees: []
            }
        },

        methods: {
            getEmployees() {
                axios.get('/api/employees')
                    .then((response) => {
                        this.employees = response.data;
                        console.log(this.employees);
                      }
                   )


            }
        },

        created() {
            this.getEmployees()
        }
    }
</script>

Within .then() you should do the rest of changes after.

Upvotes: 1

Related Questions