modify my code so that when the user input something that is not on the api the loading animation will stop and display the ‘error message’

modify my code so that when the user input something that is not on the api the loading animation will stop and display the ‘error message’. Here is my code,

import React, { useState, useEffect } from 'react';
import styled, { keyframes } from 'styled-components';
import { FaYoutube } from 'react-icons/fa';
import { useTranslation } from 'react-i18next';

const YouTube = () => {
const [userInput, setUserInput] = useState('');
const [bestVideo, setBestVideo] = useState(null);
const [books, setBooks] = useState([]);
const [relatedVideos, setRelatedVideos] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);

const getApi = async () => {
try {
setLoading(true);
const url = https://youtube-search-and-download.p.rapidapi.com/search?query=${encodeURIComponent(userInput)};
const options = {
method: 'GET',
headers: {
'x-rapidapi-key': 'f57a68517dmsh212c0ab56fd5f99p1f4a87jsna8143f942ba8',
'x-rapidapi-host': 'youtube-search-and-download.p.rapidapi.com'
}
};

  const response = await fetch(url, options);
  const result = await response.json();

  // Check if the query returned any results
  if (result.contents.length === 0) {
    setError(true);
    setLoading(false);
    setBestVideo(null);
    setRelatedVideos([]);
    await getBooks(); // Display getBooks() if getApi() fails
    return;
  }

  // Find the "best" video
  const bestVideo = result.contents.reduce((prev, curr) => {
    const prevViewCount = parseViewCount(prev.video.viewCountText);
    const currViewCount = parseViewCount(curr.video.viewCountText);
    if (prevViewCount > currViewCount) {
      return prev;
    } else {
      return curr;
    }
  }, result.contents[0]);
  setBestVideo(bestVideo);

  // Get up to 5 related videos
  const relatedVideos = result.contents.filter((video, index) => index !== 0 && parseViewCount(video.video.viewCountText) > 10000).slice(0, 5);
  setRelatedVideos(relatedVideos);

  // Call getBooks() to fetch books
  await getBooks();

  // Reset error and loading state
  setError(false);
  setLoading(false);
} catch (error) {
  console.error(error);
  setError(true);
  setLoading(false);
  setBestVideo(null);
  setRelatedVideos([]);
  await getBooks(); // Display getBooks() if getApi() fails
}
};

const getBooks = async () => {
try {
setLoading(true);
const url = https://openlibrary.org/search.json?q=${encodeURIComponent(userInput)};
const response = await fetch(url);
const result = await response.json();

  // Check if the query returned any results
  if (result.docs.length === 0) {
    setError(true);
    setLoading(false);
    setBooks([]);
    await getApi(); // Display getApi() if getBooks() fails
    return;
  }

  // Get the top 5 books
  const topBooks = result.docs.slice(0, 5);
  setBooks(topBooks);

  // Reset error and loading state
  setError(false);
  setLoading(false);
} catch (error) {
  console.error(error);
  setError(true);
  setLoading(false);
  setBooks([]);
  await getApi(); // Display getApi() if getBooks() fails
}
};

const handleBookClick = (bookKey) => {
window.open(https://openlibrary.org/${bookKey}, '_blank');
};

const parseViewCount = (viewCountText) => {
const numericPart = viewCountText.replace(/D/g, '');
const multiplier = viewCountText.includes('K') ? 1000 : 1;
return parseInt(numericPart, 10) * multiplier;
};

const handleInputChange = (e) => {
setUserInput(e.target.value);
};

const handleKeyPress = (e) => {
if (e.key === 'Enter') {
getApi();
}
};

const handleButtonClick = () => {
getApi();
};

const handleThumbnailClick = (videoId) => {
window.open(https://www.youtube.com/watch?v=${videoId}, '_blank');
};

const { t, i18n } = useTranslation();

return (
<div>
<input type="text" value={userInput} onChange={handleInputChange} onKeyPress={handleKeyPress} />
<button onClick={handleButtonClick} disabled={loading}>
{loading ? <LoadingSpinner /> : 'Search'}
</button>

  {books.length > 0 && (
    <div>
      <h2>Top Books:</h2>
      {books.map((book, index) => (
        <BookContainer key={index} onClick={() => handleBookClick(book.key)}>
          <BookImage
            src={https://covers.openlibrary.org/b/id/${book.cover_i}-M.jpg}
            alt={book.title}
          />
          <BookTitle>{book.title}</BookTitle>
          <BookAuthor>by {book.author_name?.[0]}</BookAuthor>
        </BookContainer>
      ))}
    </div>
  )}

  {bestVideo && (
    <CurvedContainer>
      <CurvedImage
        src={bestVideo.video.thumbnails[0].url}
        alt={bestVideo.video.title}
        onClick={() => handleThumbnailClick(bestVideo.video.videoId)}
      />
      <YoutubeLogoContainer>
        <FaYoutube size={50} color="#ff0000" />
      </YoutubeLogoContainer>
    </CurvedContainer>
  )}

  {relatedVideos.length > 0 && (
    <div>
      <h2>Related Videos:</h2>
      {relatedVideos.map((video, index) => (
        <RelatedContainer key={index}>
          <RelatedImage
            src={video.video.thumbnails[0].url}
            alt={video.video.title}
            onClick={() => handleThumbnailClick(video.video.videoId)}
          />
          <RelatedYoutubeLogoContainer>
            <FaYoutube size={30} color="#ff0000" />
          </RelatedYoutubeLogoContainer>
        </RelatedContainer>
      ))}
    </div>
  )}

  {/* Only display the error message if the user has provided input, the loading is finished, and there are no matching books or videos */}
  {userInput.trim() !== '' && userInput === handleInputChange && !loading && bestVideo === null && books.length === 0 && (
    <p>Sorry, no videos or books that match your input. Please change it.</p>
  )}
</div>
);
};

export default YouTube;

Basically I want the loading animation to stop then display the ‘error message’ also stop fetching the api so the console is not filled up with error fetching.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật