'Error handling in React - undefined errors

I have this code:

import "./styles.css";
import "mvp.css";
import { useState } from "react";
import axios from "axios";

function Books() {
  const [book, setBook] = useState("");
  const [result, setResult] = useState([]);
  const [apiKey, setApiKey] = useState(
    ""
  );
  function handleChange(event) {
    const book = event.target.value;

    setBook(book);
  }

  function handleSubmit(event) {
    event.preventDefault();

    axios
      .get(
        "https://www.googleapis.com/books/v1/volumes?q=" +
          book +
          "&key=" +
          apiKey +
          "&maxResults=20"
      )
      .then((data) => {
        setResult(data.data.items);
      })
      .catch((error) => {
        if (error.response) {
          alert("No results found.");

        } else if (error.request) {
          alert("No results found.");

        } else if (error.message) {
          alert("No results found.");

        }
      });
  }

  return (
    <div className="App">
      <h1>Search For A Book</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <input
            type="text"
            onChange={handleChange}
            className="input"
            placeholder="Search..."
          />
          <button type="submit">Go!</button>
        </div>
      </form>
      {result.map((book) => (
        <a target="_blank" href={book.volumeInfo.previewLink}>
          <img src={book.volumeInfo.imageLinks.thumbnail} alt={book.title} />
        </a>
      ))}
    </div>
  );
}

export default function App() {
  return <Books />;
}

And I am trying to do some error handling, and I get my alert messages as expected, however after I click off the alert box I get redirected to a typeerror that says:

book.volumeInfo.imageLinks is undefined

I am trying to suppress this and just go back to the default screen, but I am not sure how to accomplish this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source