MattB
4 months ago
406
1
Vue

Vuejs array not populating from Axios request

Posted 4 months ago by MattB

I have an Axios request pulling a JSON object from my DB as it should, and it shows ok in the console.log window as an array as expected but when I go to query the array to loop through it to show the data, it just shows blank data. Not sure what I did wrong, maybe it's a lifecycle hook problem with the data not loading quickly enough? If so, how do I get around that?

<template>
    <v-col cols="8">
        <h1 class="display-2 my-4">
            Page Heading
            <ul>
                <li v-for="p in posts" :key="p.id">
                    {{ p.title }}
                </li>
            </ul>
            <p class="headline">Secondary Text</p>
        </h1>
        <div v-for="p in posts" :key="p.id">
            <v-card class="mx-auto mb-4" max-width="750">
                <v-img
                    class="white--text align-end"
                    height="200px"
                    src="https://cdn.vuetifyjs.com/images/cards/docks.jpg"
                >
                    <v-card-title>{{ p.title }}</v-card-title>
                </v-img>

                <v-card-text class="text--primary">
                    <div>Written By: {{ p.posted_by }}</div>

                    <div>{{ p.post }}</div>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="orange" text>
                        Share
                    </v-btn>
                    <v-btn color="orange" text>
                        Explore
                    </v-btn>
                </v-card-actions>
            </v-card>
        </div>
    </v-col>
</template>

<script>
export default {
    data: () => ({
        posts: [],
    }),
    created() {
        this.posts = [];
        axios.get('/api/posts').then(res => {
                this.posts = res.data;
                console.log(this.posts)
            })
            .catch(err => {
                console.log(err);
            });
    },
};
</script>
<style lang="scss" scoped></style>

For reference, this is the data I'm passing into it: https://jsoneditoronline.org/?id=2ab8a589187f4b50918e51e7ad4c02eb

Please sign in or create an account to participate in this conversation.