I have an object in vuex that im getting on the page by getters, but vue see only first update of object. I collect the object stepwise so first it’s empty then i have commit that updates vuex state (setUser) and vue showing this new info on the page. But then i use one more commit (addInfo) and it’s works I can see updated info using Vue DevTools, but i can’t use it on the page it’s showing second state
async fetchUser({ commit, state }) { return new Promise(() => { axiosInstance .get(User(), { headers: { Authorization: 'Token ' + localStorage.getItem('token'), }, }) .then((res) => { commit('setUser', res.data); }) .then(() => { axiosInstance.get(UserID(state.userInfo.pk)).then((res) => { axiosInstance.get(res.data.profile).then((res) => { commit('addInfo', res.data); console.log(state.userInfo); }); }); }) .catch((err) => { console.log(err); }); }); }
Object called userInfo im getting on the page by
computed: { ...mapGetters(['userInfo']), }, created() { this.$store.dispatch('fetchUser'); }
This is what i get on the page
This is how the object really looks like
Advertisement
Answer
This is a common reactivity issue, there are multiple solutions on you’ll get used to it:
Basically Vue can not detect property addition on objects due to JS limitations, to solve it your initial state.userInfo
should have all keys you want to have reactivity, you can just set them to null
, ''
, or 0
depending on type.
userInfo: { //all my userInfo reactive keys 1stkey: '', 2ndkey: null, 3rdkey: 0, ... 100thkey: '', }
You can also set your state.userInfo = null
initially to null so you can detect when it gets filled.
Check here for more info of Vue Reactivity on Vue docs