hidar
hidar

Reputation: 5949

computed property not reading data initialized in created

I am not sure when computed property (in vue lifecycle) comes. Let's say I have a method that I run in created() as:

created () {
  getSomething()
}

Inside getSomething() I fetch data and fill my data property as:

getSomething(){
 axios.get(...) { this.info = response.data }
}

Now, in computed properties, I do:

computed: {
  doSomething () {
    this.info.forEach(item => {})
 }
}

But, inside my computed I get forEach is undefined, as if this.info is not an array or has not be filled.

What am I doing wrong? are computed props called before created() or something?

Upvotes: 1

Views: 2014

Answers (2)

Francis Leigh
Francis Leigh

Reputation: 1960

You could utilise Vuex' state management...

Vuex has :

  • Dispatches

  • Actions

  • Mutations

  • Getters

What i am thinking is, on your page load, map an action to the store that makes a call to your axios service and after it returns, commit a mutation that stores the response to the store... then you can map the state to your component and retrieve the data.

This might not be the quickest answer but if you are expecting to need the response data from the axios request, it might be worth putting it into some sort of state management :-)

Upvotes: 2

JoWinchester
JoWinchester

Reputation: 437

try something like this

getSomething(){
 return axios.get(...) { this.info = response.data }
}

then you can use the promise returned in created method like this....

created () {
  getSomething().then( () => {
    doSomething()
  }}
}

Upvotes: 2

Related Questions