Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bicicura's avatar

Display image only if property exists

Hello!

I'm developing a small app that allows the user to find book/books by searching the Google Books API. The user types in an input with the book title or author and the API responds with an array with the books that match the query. It works great!

The issue is that I also want to display the thumbnail of the book that the API provides, yet some items (books) in the API response don't have this property item.volumeInfo.imageLinks.thumbnail that is the path to the thumbnail. So, when I am looping on the view with a v-for in some cases this error message pops because the property cannot be found and the app breaks.

SearchResults.vue:6 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'thumbnail')

How can I display the image only if this property of the iterated item exists?

Here is the view code

<ul>
        <li v-for="item in books.items" :key="item.id" >
            <div>
                <img :src="item.volumeInfo.imageLinks.thumbnail"/>
            </div>
            <a :href="item.volumeInfo.infoLink" target="_blank" class="hover:underline" v-text="item.volumeInfo.title"></a>
            <div>
                <span>By</span>
                <p v-for="(author, index) in item.volumeInfo.authors" :key="index">
                    <span>{{author}}</span>
                    <span v-if="index < item.volumeInfo.authors.length - 1">, </span>
                </p>
            </div>
        </li>
    </ul>
0 likes
1 reply
bicicura's avatar
bicicura
OP
Best Answer
Level 7

Nailed it with this conditional

<div v-if="item.volumeInfo.hasOwnProperty('imageLinks')">
	<img :src="item.volumeInfo.imageLinks.thumbnail"  />
</div>

If someone has another way, I would be glad to hear it!

1 like

Please or to participate in this conversation.