1
votes

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!

1
did you try out img :src="aboutData?aboutData.photo.name:''">?Boussadjra Brahim
Have you tried adding conditional rendering while you await the data? <img v-if="aboutData"/ :src="aboutData.photo.name"> - if this would work then your suspicions are rightMichał Sadowski
thanks for these replies. these suggestions would make the error go away, but I want to understand why the error is appearing and how I can reorganize my code to prevent it. Again, the photo and the rest of the data is rendering on the page, so I'm not sure what the error is aboutajohnson10209

1 Answers

2
votes

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.