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?
CodePudding user response:
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
CodePudding user response:
I had this problem. You can use the following code as an example:
:style="{ 'background-image': 'url(' item.cover_media.url ')' }"