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.