0👍
As you said, it’s rendering before the data has loaded.
The problem is that you’re defaulting the store state to song: {}
, so v-if="getSong"
is always going to be true.
A quick fix would be v-if="getSong.owner"
instead. Personally I wouldn’t fix it that way, I’d change it to song: null
and handle the missing song higher up the template. Ultimately you need to make a decision about what you want to render while the data is loading. Locally that might take milliseconds but you should consider how long it might take in production and what you want your users to see.
On an unrelated note, you shouldn’t be wrapping axios calls in promises. Axios returns promises anyway so you should just return those. e.g.:
UPLOAD ({commit}, payload) {
return Axios.post('/song', payload)
})
Update:
The created
hook will run before rendering occurs but you’re making asynchronous requests and it won’t wait for those to complete before proceeding with rendering.
At the point it first renders the store state will still contain your default values. In most places the way your template is handling those defaults won’t cause an error, except for the getSong.owner.profile
part. getSong
will be an empty object, so getSong.owner
will be undefined
, leading to an error trying to access its profile
property.
Note that just because the other values aren’t causing an error doesn’t necessarily mean they are working ‘correctly’. While the real values are loading the user will see a partially populated UI. This is unlikely to be desired in the finished application.
When the real values load it will render again, this time without errors. A setTimeout
is unnecessary, you just need to write your template to handle the missing data.
One way to do this, as mentioned earlier, is to set song: null
and move the v-if="getSong"
further up the template, so that nothing tries to use getSong
.
0👍
Okay so i fixed the problem. For all those who are having the same problem and work with express and mongoose. It seems mongoose was causing the problem because i had 2 populates in 1 call. I changed the order in which the populates happened and somehow the error disappeared.