I'm really stuck on this issue. I've been trying to retrieve a blog post object using a getter based on its "slug". Despite all my attempts, every time I try to use the getter, I keep getting an error saying "state.posts.filter" is not a function. I know for sure that there are items in the state array and it is defined as an array by default. Any thoughts on why this might be happening? Assuming that FETCH_POSTS has already been dispatched and that posts contains elements.
Not sure if this matters, but I am working with Nuxt in the modular store format.
This is how my Store looks:
import {createClient} from '~/plugins/contentful.js'
const client = createClient()
const state = {
posts: []
}
// getters
const getters = {
allPosts: state => state.posts,
getPostBySlug: state => slug => state.posts.filter(post => post.fields.slug === slug)
}
// actions
const actions = {
FETCH_POSTS: (state) => {
// INIT LOADING
client.getEntries({
'content_type': 'article',
order: '-sys.createdAt'
})
.then(posts => {
// SUCCESS
state.commit('SET_POSTS', posts.items)
})
.catch(error => {
// FAILURE
console.log(error)
})
}
}
// mutations
const mutations = {
SET_POSTS: (state, posts) => {
// Assign posts to state
posts = posts.map(function (post) { post.fields.slug = post.fields.title.replace(/\s+/g, '-').toLowerCase()
return post
})
state.posts = Object.assign({}, posts)
}
}
export default {
state,
getters,
actions,
mutations
}
And in my component, I call it like this:
export default {
name: 'blog-post',
computed: {
post: function () {
return this.$store.getters.getPostBySlug('test-slug')
}
}
}