W
W
wlms2019-03-08 11:14:30
Vue.js
wlms, 2019-03-08 11:14:30

How to get vuex asynchronous state?

store/profile.js
import Axios from 'axios'

const state = {
  profile: null
}

const actions = {
 loadProfileOnce: async ({commit}, id) => {
    try {
      const {data} = await Axios.get('http://127.0.0.1:3001/api/profile/' + id)
      console.log(data)
      if (data) {
        commit('loadProfileOnce', data)
      } else {
        console.log('errorororo')
      }
    } catch (error) {
      throw error
    }
  }
}

const mutations = {
  loadProfileOnce: (state, payload) => {
    state.profile = payload
  }
}

const getters = {
  getOneProfile: state => {
    return state.profile
  }
}


In the component I write like this:
profile.vue
created () {
    this.$store.dispatch('loadProfileOnce', this.profileId)
  },
  computed: {
    ...mapGetters(['getOneProfile'])
  },


An object arrives. When I access {{ getOneProfile}} it renders the object normally, but when I render the property in the {{ getOneProfile.profile.name }} template it throws rendering errors. It is clear that the matter is in asynchrony. I don't understand what I'm doing wrong and how to fix it to make it work.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2019-03-08
@smlwmy

getOneProfile: state => {
  return state.profile
}

That is, does state.profile have a profile property? Like, could you also write $store.state.profile.profile.name? I suspect that the profile is still superfluous. Well, in order not to try to display data that is not there yet, use conditional rendering: UPD. Taken from the comments:
Well do:
<КакойТоКомпонент v-if="данные" />
<ИндикаторЗагрузки v-else />

A
Alexander Drozdov, 2019-03-08
@bagzon

{{ getOneProfile.profile.name }}
getOneProfile already returns profile, maybe this is the problem?
try {{ getOneProfile.name }}

V
Vladimir, 2019-03-08
@z3d01n

You just need to tell Vue to wait. Those. make created asynchronous.

async created () {
   await this.$store.dispatch('loadProfileOnce', this.profileId)
  },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question