Uncaught (in promise) TypeError: Cannot read properties of null (reading 'path')

Viewed 4025

My images arent displayed and Im getting error from the title. This is my code:

<theme-card
  v-for="theme in themes"
  :router-link="`/theme/${theme.slug}`"
  :key="theme.id"
  :name="theme.name"
  :tags="theme.tags"
  :id="theme.id"
  :imgPath="theme.image.path"
></theme-card>

this is my get request

async getThemes() {
  await axios.get('api')
             .then((response) => (this.themes = response.data.data))
},

then in mounted:

async mounted() {
  await this.getThemes()
}

in Theme card I receive img path as prop

<img :src="`${imgPath}`" alt="theme-img" height="80" />

everything works without an image, so my get request and v-for works, only theme.image.path doesnt work and i dont know why, im using vue and ionic

2 Answers

To display just the images which has paths, you can try the below code

<theme-card
    v-for="theme in themes"
    :router-link="`/theme/${theme.slug}`"
    :key="theme.id"
    :name="theme.name"
    :tags="theme.tags"
    :id="theme.id"
    :imgPath="theme.image? theme.image.path : ''"
></theme-card>

It seems that theme.image is not defined for some cases. To still display the list, simply use:

<theme-card
    v-for="theme in themes"
    :router-link="`/theme/${theme.slug}`"
    :key="theme.id"
    :name="theme.name"
    :tags="theme.tags"
    :id="theme.id"
    :image="theme.image"
></theme-card>

and then v-if to conditionally display the image

<img v-if="image" :src="`${image.path}`" alt="theme-img" height="80" />
Related