I'm trying to get a better understanding of the lifecycle of a Nuxt app that is statically generated and could use some help.
I've been running into issues where data
attributes will not be set if I rely on mounted
to initialize it and I'm not totally sure why.
For example, lets say I have the following setup to load data using fetch
and computed
properties.
async fetch ({store, params}) {
const data = await store.dispatch('fetchData', params.id)
store.dispatch('setData', data)
},
computed: {
data () {
return this.$store.getters.loadedData
}
}
This works fine, but now if I want to use a v-model
I need to add a data
property since computed property doesn't make sense here.
data () {
selectedId: null
},
mounted () {
this.selectedId = this.$store.getters.loadedData.id
}
When I do this, this.selectedId
is not set if I do a page refresh, it will work the first time if I navigate to the page from another URL. There's something about the order of operations or timing when a page refresh occurs that doesn't run mounted
as expected. I know it's running because I can do console.log
and see them but the value for this.selectedId
is not being set. I'm assuming it's because the store
is not ready yet by this point.
So as a hack, I can wrap it with nextTick
mounted () {
this.$nextTick(() => {
this.selectedId = this.$store.getters.loadedData.id
})
}
And it works now... but this doesn't seem right.
What's the best practice here for setting component data
that relies on the store? I can't use the fetch
method because the component is not accessible here.