1

I have v-for loop in html, in my localhost everything works fine, but whenever I deploy to production I keep getting this error TypeError: Cannot read property 'url' of null , even though the url exists in the objects.

<div v-for="item in items" :key="item.id">
<div :style="{ backgroundImage: (`url(${item.cover_media.url}`)}")></div>
</div>

I am trying to use this solution: https://stackoverflow.com/a/54591429/16897778

This is the only item I have and u can see the image is loaded

but console still throws and whenever I add more items, it can't fetch more than 1. How can I fix this issue?

Dave
  • 1
  • 1
  • 9
  • 38
  • it looks like your `item` or `cover_media` property is `null`. Have you verified that these are not null using a devtool? – mcy Sep 28 '21 at 08:58
  • 1
    I think the issue is the component renders before the cover_media is here, how can I make sure the url will load whenever it exists? – Dave Sep 28 '21 at 08:59
  • Make sure each item's cover_media value is not null. If not sure, use `item.cover_media?.url` instead. – lry Sep 28 '21 at 09:00
  • @ruoyanli will it not return undefined and not load the item? – Dave Sep 28 '21 at 09:05
  • AFAIR vue object properties are reactive; it will load nothing at first, then update the values when `.url` has changed. – mcy Sep 28 '21 at 10:05

2 Answers2

1

If you're concerned that that the component renders before cover_media is fetched, you can give a default value to the url like so:

<div v-for="item in items" :key="item.id">
    <div :style="{ backgroundImage: (`url(${item?.cover_media?.url || default_image_url}`)}")></div>
</div>

So the default image will be loaded then once the images load, it will change to the url in item?.cover_media?.url

Another thing you can do is only load that element after your data is fetched.

You can easily do that but here's a simple excerpt:

<template v-if="fetched">
    <div v-for="item in items" :key="item.id">
        <div :style="{ backgroundImage: (`url(${item?.cover_media?.url}`)}")></div>
    </div>
</template>

<script>
data() {
   return {
      fetched: false,
      items: []
   }
},
methods: {
    fetchImages() {
        const response = await executeGetRequest()

        if (response.status === 200) {
            this.items = response.data.items;
            this.fetched = true
        }
    }
}
</script>

PS. I was eating a banana while I saw this question and noticed your username so I felt inclined to answer this question haha

Ayudh
  • 1,673
  • 1
  • 22
  • 55
1

I had this problem. You can use the following code as an example:

‍‍‍‍‍‍:style="{ 'background-image': 'url(' + item.cover_media.url + ')' }"