I'm trying build my homepage, and, obviously, I've chosen Nuxt.js as my application framework. Also I'm trying to use Contentful as my content deliverer.
I didn't like contentful
npm package, as Contentful interface, so I decided to create own, with Vuex store.
Contentful doesn't provide static content types, it allows to create an arbitrary type, and associate content with it.
At this point I need to hold data only, and since I don't know data type from semantics point of view, I need just an empty state. So I didn't create any properties on state
object like so:
contentful = {
state: {}
}
Then I made a mutation
which should define new property with specific name:
mutations: {
defineEntryType: (state, payload) {
state[pluralize(payload.name.toLowerCase())] = payload
}
}
Also I needed to push actual entries somehow:
mutations: {
pushEntries: (state, payload) {
const typeName = pluralize(payload.type.name.toLowerCase())
state[typeName].items = state[typeName].items || []
state[typeName].items.push(payload.item)
}
}
}
Next thing I need to actually use this crafty mutations, so I made a huge method and placed it in nuxtServerInit
:
actions: {
nuxtServerInit ({ commit }) {
axios.get(TYPES_ENDPOINT).then(res => {
res.data.items.map(type => {
commit('defineEntryType', type)
axios.get(ENTRIES_ENDPOINT, {params:
{content_type: type.id}
}).then(res => {
res.data.items.map(item => {
commit('pushEntries', {type: type, item: item})
}
}
}
}
}
}
Lastly I needed some getters in order to access state
in a convenient way:
getters: {
getEntriesByTypeName: state => type => state[type].items,
getEntryBySlugName: state => type, slug => state[type].items.find(item => item.slug === slug)
}
And this is where fun begun.
Since I'd like to host my page on GitHub Pages, I'd like my page to be completely ready to delivery, so I use nuxt generate
. It works, periodically. When does not work, it yanks an error TypeError: Cannot read property 'items' of undefined
. Obviously, my property definer wasn't able to pull its job.
Even more fun when nuxt generate
reports successful built, but the same error gets to the browser console.
So, my question is: how to use nuxtServerInit
action for statically generated sites?
PS: I started to notice that on dev
, store also misbehaves. Firstly it won't even create itself, then, after page reload, it ready and even with dynamically defined properties, but without prop items
on 'em, and after the second reload content entries are pushed to target items
array.
PPS: Sorry, if this issue doesn't comply with your rules. Even though I really need help, so if it is inappropriate, point me where and I cooperate.
Any input appreciated, thank you in advance!
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c843">#c843</a>)</em></sub></div>