I want to check if the property url is set on the item object, if it's not there I want to display a placeholder image. Something like this:
<img
v-if="item.relationships.main_image.attributes.url"
:src="item.relationships.main_image.attributes.url"
:alt="item.attributes.name"
class="h-full w-full"
/>
<img v-else :src="require('@/assets/placeholder.png')" alt=""/>
The problem is that my item object may not have any properties, as backend only send those properties if there is actually an image linked to the item.
How can i check if an object has that deep property?
Error given: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'attributes')
You can simplify this and get rid of this extra img tag. Also if any of item object properties can be null you can use optional chaining (e.g. item?.relationships...).
I don't know which property can and cannot be null, so lets assume the worst case scenario:
<img :src="item?.relationships?.main_image?.attributes?.url || require('@/assets/placeholder.png')"
:alt="item?.attributes?.name || 'placeholder'"
class="h-full w-full"/>