Reputation: 2309
I have Vuex storage, where i store 'user' (obj uploaded from server)
In main App.vue in created section i always fill 'user'
It's async method. My components dont wait. When i use in template {{user.logo}} i got error in console 404
http://example.net/images/undefined
But in next second, when user uploaded, error gone.
How make app wait uploaded async date in Vuex?
Updated. I understand why this is happening. Component mounted, async data not ready. I make state 'ready' in Vuex, its become true after success upload. I check 'ready' in computed section. if not ready it return no_logo.png
But, in my component, in created section, when i fetch other data from server by 'user.id' from Vuex store (but user not yet ready) i got error. How check 'ready' in created section before fetching?
//html
<div id='app'>
<ul>
<li v-for='role in roles'>
<p>{{role}}</p>
</li>
</ul>
</div>
//script Vue
var app = new Vue({
el: '#app',
data: {
roles: []
},
created: {
this.fetchingItems() //GOT ERROR need check Ready!!!
},
methods: {
fetchingItems() {
axios.get('api/getRoles/${this.$store.user.id}')
.then((res) => this.roles = res.data.roles)
}
}
})
// This is store!!!.
const store = new Vuex.Store({
state: {
ready: false,
user: {}
},
mutations: {
USER_SET(state, user) {
state.user = user
},
READY_SET(state) {
state.ready = true
}
},
action: {
loadUser() {
axios.get('api/getUser/${parseInt(localStorage.getItem('user_id'))}')
commit('USER_SET', res.data.user)
commit('READY_SET')
}
}
})
Upvotes: 2
Views: 3568
Reputation: 2309
i fix it!
use watch.
watch: {
ready: function () {
this.fetchingItems()
}
},
Upvotes: 1
Reputation: 4580
It will happen that because the user information is not there when the component is mounted, but it will be there eventually.
In this image, you are dispatching and action, asking Backend API for data and then commiting to the store.
Until the commit everything in the component will not be filled with the actual data.
What you need to do is use v-if
to show or not the component.
Other way is to show an overlay until all data is loading like this:
Upvotes: 2