I have got a new method of making this work. Basically I made a different component for rendering, and passed properties through props. I then used try and catch in the component where i map the array, and before sending the props, I try for error, if there's no error, it passes normally image links. if there's an error, I would pass image property as "", which basically means empty string in img tag. I will attach the code. its rough code, with console.logs, but main thing is inside the try and catch
main driver code
import React, { useEffect, useState } from 'react';
import Details from './bookDetails';
import './books.css'
export default function Books2() {
const [bookName, setName] = useState("a");
const [load, setLoad] = useState(false)
const [itemArray, setArray] = useState([]);
useEffect(() => {
loadData();
}, [])
async function loadData() {
setLoad(true);
// console.log(bookName)
await fetch("https://www.googleapis.com/books/v1/volumes?q=intitle:"+bookName)
.then(response => response.json())
.then(data => setArray(data.items))
setLoad(false)
}
function handleChange(event) {
// console.log(event.target.value)
setName(event.target.value)
}
function handlePress() {
loadData();
}
// console.log(itemArray)
var className = (load===true) ? "loading" : "null"
return (
<div>
<h1>Hello</h1>
<input placeholder="book name" value={bookName} onChange={handleChange} />
<button onClick={handlePress}>Search</button>
<h3 className={className}>Loading...</h3>
{/* <input placeholder="name of book" value={} /> */}
{itemArray.map(book => {
{/* console.log(book.volumeInfo.imageLinks) */}
try{
return(
<Details
key={book.id}
bookName={book.volumeInfo.title}
bookYear={book.volumeInfo.publishedDate}
bookDesc={book.volumeInfo.description}
bookLink={book.volumeInfo.infoLink}
bookImg={book.volumeInfo.imageLinks.smallThumbnail}
/>
)}
catch(err) {
<Details
key={book.id}
bookName={book.volumeInfo.title}
bookYear={book.volumeInfo.publishedDate}
bookDesc={book.volumeInfo.description}
bookLink={book.volumeInfo.infoLink}
bookImg={""}
/>
}
})}
{/* <button onClick={handlePress}>Search</button> */}
</div>
)
}
component for rendering code
import React from 'react';
export default function Details(props) {
return(
<div>
<h1>{props.bookName}</h1>
<a href={props.bookLink} target='_blank'>Link to book</a>
<img src={props.bookImg} className="img"/>
<h3>{props.bookYear}</h3>
{/* <h4>{bookPage}</h4> */}
{/* <h5>{bookRating}</h5> */}
<p>{props.bookDesc}</p>
</div>
)
}