Sorry if this is really obvious but I’m new to Vue and could use some help.
I’m grabbing an array of data (posts) from my store and trying to console log just one of the objects in the array, but it’s showing undefined every time. If I console log the whole array it returns fine.
I’m guessing this is something to do with the data not loading before the console.log in the created hook? I’ve tried everything I can and it’s driving me nuts. Any help appreciated (simplified code below).
<script>
export default {
components: {},
computed: {
posts() {
return this.$store.state.posts;
}
},
created() {
this.$store.dispatch("getPosts");
console.log(this.posts[0])
},
};
</script>
//Store code Below
export const state = () => ({
posts: [],
})
export const mutations = {
updatePosts: (state, posts) => {
state.posts = posts
}
}
export const actions = {
async getPosts({
state,
commit,
dispatch
}) {
if (state.posts.length) return
try {
let posts = await fetch(
`${siteURL}/wp-json/wp/v2/video`
).then(res => res.json())
posts = posts
.filter(el => el.status === "publish")
.map(({
acf,
id,
slug,
video_embed,
title,
date,
content
}) => ({
acf,
id,
slug,
video_embed,
title,
date,
content
}))
commit("updatePosts", posts)
} catch (err) {
console.log(err)
}
}
}