+ Start a Discussion
ankita sharma 2110ankita sharma 2110 

[Cannot read property 'smallThumbnail' of undefined]

I am trying to pull values from Googlebooks API for my LWC. Below is my code-->
<template if:true={books}>
                    <template for:each={books.items} for:item="book">
                        <lightning-layout-item size="3" padding="around-small" key={book.id}>
                            <div class="slds-box slds-p-around_medium slds-text-align_center">
                              <img src={book.volumeInfo.imageLinks.smallThumbnail} height="200px">
                              <div class="slds-text-heading_small slds-p-vertical_medium"><strong>{book.volumeInfo.title}</strong></div>
                              <div> <strong>Published Date- {book.volumeInfo.publishedDate}</strong></div>
                              <div> <strong>Average Rating- {book.volumeInfo.averageRating}</strong></div>
                              <!--div><strong>Categories</strong><span>{book.voumeInfo.categories}</span></div-->
                            </div>

JS Code->const BOOK_URL = 'https://www.googleapis.com/books/v1/volumes?q='
export default class BookApp extends LightningElement {
    query='Man'
    books
    connectedCallback(){
        this.fetchBookData()
    }
    fetchBookData(){
        fetch(BOOK_URL+this.query)
    .then(Response=>Response.json())
    .then(data=>{
        console.log(data)
    this.books = data
    })
    .catch(error=>console.error(error))
    }
}


For both the categories and small thumbnail i am getting error -> [Cannot read property 'smallThumbnail' of undefined]
Best Answer chosen by ankita sharma 2110
veer soniveer soni
hy Ankita,
try below code.
import { LightningElement, track } from "lwc";
const BOOK_URL = 'https://www.googleapis.com/books/v1/volumes?q=Man';
export default class FetchDataFromThridPartyInLwc extends LightningElement {
   query='Man'
  books
  connectedCallback(){
      this.fetchBookData()
  }
  fetchBookData(){
      fetch(BOOK_URL+this.query)
  .then(Response=>Response.json())
  .then(data=>{
      console.log('fetch Data from Third Party : ' + JSON.stringify(data));
  let thirdPartyData = data;

let newData = [];
  for(let i=0; i<thirdPartyData.items.length; i++){
    console.log('eachItem : ' + JSON.stringify(thirdPartyData.items[i]));
    let eachItem = thirdPartyData.items[i].volumeInfo;
    if(eachItem.imageLinks == undefined){
        thirdPartyData.items[i].volumeInfo.imageLinks = {"smallThumbnail" : "#####"};
        }
  }
  console.log('thirdPartyData : ' + JSON.stringify(thirdPartyData));
  this.books = thirdPartyData
  })
  .catch(error=>console.log('Third Party Error : ' + JSON.stringify(error)))
  }
}

your error was coming because in actual data imageLinks  this property was not coming in 3-4 item so I did handle them. use above code.
don't forget to mark it as best answer.
Thank you​​​​​​​