ajohnson10209
ajohnson10209

Reputation: 664

Vuex - getting an undefined error when using getter in computed

The data on my vue js website is rendering, but I'm getting an undefined error in the console. I'm making an axios call in App.vue to go get data from my cms:

App.vue

async created() {

const strapiData = await getStrapiData();

// Update Vuex
this.$store.dispatch('setStrapi', strapiData);

}

then in one of my components, I'm calling the getter to retrieve the data that's stored in vuex:

About.vue

computed: {
    aboutData() {
        return this.$store.getters.strapiData.data.about
    }
}

Which I then reference in my template code:

<img :src="aboutData.photo.name">

Everything renders fine, but this is the error I'm seeing in the web console:

TypeError: Cannot read property 'photo' of undefined
at a.r (About.vue?3e5e:1)

I think the issue has something to do with the order in which my components are being created. I'm importing all of my child components into App.vue rendering them there, but I think the child components are being created before the created lifecycle hook of app.vue :

App.vue script

components: {
'app-about' : About,

App.vue template

<template>
  <div id="app">
    <app-about></app-about>
  </div>
</template>

Any one have an idea of what I'm missing? Thank you!

Upvotes: 2

Views: 1028

Answers (1)

catmal
catmal

Reputation: 1758

When first the component is created the axios call is not resolved yet so aboutData is undefined. As soon as the call is resolved aboutData is rendered. Getting it undefined and rendering are 2 subsequent events. Using v-if eliminates the first event as aboutData is not called when the component is created but only when the axios call has resolved and aboutData is available.

What you usually do is set a property loading with default as false. Then you set loading to true when axios call starts, and set it to false when is resolved. And in your template you set some "Loading Message" to show while loading is true.

Upvotes: 2

Related Questions