Reputation: 129
I'm stuck to get the data from the database through Axios using Vue.js. In Vue.js developer tools I can get the data from my database like this:
But when I loop using v-for
like this:
<template>
<div class="flex flex-col items-center py-4">
<NewPost></NewPost>
<Post v-for="(post,i) in posts.data" :post="post" :key="i"/>
</div>
</template>
<script>
import NewPost from "../components/NewPost";
import Post from "../components/Post";
export default {
name: "Newsfeed",
components: {
NewPost,
Post
},
data: () => {
return {
posts: null
}
},
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
console.log(this.posts)
}).catch(error => {
console.log('Unable to fetch posts')
})
}
}
</script>
<style scoped>
</style>
The console says
"[Vue warn]: Error in render: "TypeError: Cannot read property 'data' of null"
found in
---> at resources/js/views/Newsfeed.vue at resources/js/components/App.vue "
I don't understand because in Vue.js developers tools I can get the data. Is the looping wrong? Thank you!
Upvotes: 0
Views: 570
Reputation: 129
Another answer is to add the loading variable like this
In the data : data: () => { return { posts: null, loading: true } }
In the mounted()
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
this.loading = false
console.log(this.posts)
}).catch(error => {
this.loading = false
console.log('Unable to fetch posts')
})
}
Upvotes: 0
Reputation: 1
Init that nested field with an empty array like :
data: () => {
return {
posts: {
data:[]
}
}
},
Upvotes: 1