M
M
manFromRain2018-10-31 16:22:47
Vue.js
manFromRain, 2018-10-31 16:22:47

Why do not have time to load the data in the state?

There is an asynchronous action that causes a mutation and updates the state data

actions: {
    async fetchData ({commit}) {
      await axios.get('apiurl')
          .then(response => {
            commit('setData', response.data)
          })
    }
  }

In component do (component NOT main.js)
computed: {
    ...mapState(['data'])
  },
  methods: {
    ...mapActions(['fetchData'])
  },
  created () {
    if (!this.data) {
       this.fetchData()
      console.log(this.data) //undefined
    }
  }

At this stage, this.data does not have time to load. Tell me how to wait for the data correctly and why this happens.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2018-10-31
@manFromRain

actions: {
  fetchData({commit}) {
    return axios.get('apiurl').then(response => {
      commit('setData', response.data)
    })
  }
}

computed: {
  ...mapState(['data'])
},
methods: {
  ...mapActions(['fetchData'])
},
async created () {
  if (!this.data) {
    await this.fetchData();
    console.log(this.data)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question