Created
November 5, 2020 21:05
-
-
Save codebubb/ef77bd6d18d2bcd36de19b171c46c3ab to your computer and use it in GitHub Desktop.
React YouTube Viewer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
import { Search } from './Search'; | |
import { Video } from './Video'; | |
export function App() { | |
const [videos, setVideos] = useState([]); | |
const [currentChannelId, setCurrentChannelId] = useState(); | |
const [channelName, setChannelName] = useState(); | |
const [searchError, setSearchError] = useState(); // Create searchError state | |
const baseUrl = 'https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D'; | |
useEffect(() => { | |
(async () => { | |
if (currentChannelId) { | |
try { | |
const data = await fetch(`${baseUrl}${currentChannelId}`).then(response => response.json()); | |
if (!data.items) { | |
throw new Error(); | |
} | |
setVideos(data.items); | |
setChannelName(data.items[0].author); | |
setSearchError(''); // Reset the error if a successful request is received | |
} catch (error) { | |
console.log(error); | |
setSearchError(`Couldn't retrieve videos, check your channel ID.`); // Set the error state if an error occurrs | |
} | |
} | |
})(); | |
}, [currentChannelId]); | |
return ( | |
<div className="app-container"> | |
<h1>Latest YouTube Videos</h1> | |
<Search setCurrentChannelId={id => setCurrentChannelId(id)}/> | |
<div className="search__errors"> | |
{searchError} // Display any errors | |
</div> | |
{channelName && <h2>Videos from {channelName}</h2>} | |
<div className="videos"> | |
{videos.map(video => <Video key={video.guid} video={video} />)} | |
</div> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment