0

In the application I'm working on, I have a component loading data and storing them in a store. To do so, I have implemented the created function and a computed function like this :

computed: {
  initiatives: function () {
    return this.$store.state.initiatives.initiatives
  }
},
created () {
  this.$store.dispatch('initiatives/getInitiatives')
}

This allows to have an initiatives variable available from the component. To define a specific initiative, I have a variable like this :

data: function () {
  return {
    cinitiative: {}
}

What I want to do is to initialize the cinitiative variable with a random object from the loaded objects stored in this.initiatives. When I do it in the created function :

created () {
  this.$store.dispatch('initiatives/getInitiatives')
  let iindex = Math.floor(Math.random() * Math.floor(this.initiatives.length))
  this.cinitiative = this.initiatives[iindex]
}

I have this error :

TypeError: "this.cinitiative is undefined"

And I have the same error when I try to do the same from the mounted function. Where should I do it ?

user1595929
  • 1,284
  • 3
  • 13
  • 23

1 Answers1

0

As created hook is executed only once and initiatives/getInitiatives depends on a Promise, you should await for this, like:

async created () {
  await this.$store.dispatch('initiatives/getInitiatives')
  let iindex = Math.floor(Math.random() * Math.floor(this.initiatives.length))
  this.cinitiative = this.initiatives[iindex]
}

But actually a best practice is turn cinitiative into a computed property, which is reactive to initiatives:

computed: {
  initiatives: function () {
    return this.$store.state.initiatives.initiatives
  },
  cinitiative: function () {
    let iindex = Math.floor(Math.random() * Math.floor(this.initiatives.length))

    return this.initiatives[iindex]
  },
},
Matheus Valenza
  • 889
  • 1
  • 5
  • 11