Быстрое начало создания веб-приложения с API данных Youtube с Javascript и созданием приложения React.

Давайте создадим простое веб-приложение, использующее API данных Youtube. Для быстрого старта я использую приложение create-реагировать

Предыстория:
Я пыталась быстро найти видеоуроки по теням для век на YouTube. Вместо того, чтобы печатать в строке поиска, я хотел что-то, что я мог бы отметить, чтобы найти свои видео одним щелчком мыши.

Вот как я это сделал:

1. Установите node и npm здесь.
2. В терминале запустите npx create-react-app <your-app-name>
3. cd <your-app-name>
4. Отредактируйте public/index.html, добавив <script src=”https://apis.google.com/js/api.js"></script> в тег <head>.
5. В редакторе кода замените src/App.js следующим:

import “./App.css”;
import React, { useEffect, useState } from “react”;
// Notice how we don’t need extra node packages besides the ones built into create-react-app!
function App() {
 // Here we’re setting up state using useState because we’re using React Hooks with functional components.
 // In a class component we would use this.state = instead.
// We will use this to store the search results obtained by the YouTube Data API
 const [searchResults, setSearchResults] = useState([]);
 
 const colorNames = [
 “red”,
 “blue”,
 “green”,
 “yellow”,
 “orange”,
 “black”,
 “white”,
 “brown”,
 “purple”,
 “pink”,
 “gold”,
 “silver”,
 “natural”,
 “rainbow”,
 “festival”,
 “glitter”,
 ];
// Here we are using the Array.prototype.reduce method to automatically generate an object contatining checkbox states for every color.
 const [colorState, setColorState] = useState(
 colorNames.reduce((acc, color) => {
 acc[color] = false;
 return acc;
 }, {})
 );
// This code is lifted from the Google API Explorer documentation example code. However, one important change was made: We replace all instances of gapi with window.gapi to find our imported gapi object in React. Note that we’re getting this object from the script tag in our index.html
 function loadClient() {
 // Get your api key following the directions here: https://developers.google.com/youtube/v3/getting-started
 window.gapi.client.setApiKey(“<YOUR-API-KEY-HERE>”);
 return window.gapi.client
 .load(“https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
 .then(
 function () {
 // You can delete these console logs if you don’t want unneccesary logs.
 console.log(“GAPI client loaded for API”);
 },
 function (err) {
 console.error(“Error loading GAPI client for API”, err);
 }
 );
 }
// useEffect is the React hooks way to run code once when a component is mounted, similar to componentDidMount in React classes. Here we load our gapi client, setting us up to make API requests in the app.
 useEffect(() => {
 window.gapi.load(“client”, loadClient);
 });
// This is where our JSX starts and where our app is rendered and styled.
 return (
 <div className=”App”>
 <h1>Select the colors you’d like to see the tutorials of:</h1>
 <div id=”colors”>
 // We use Array.prototype.map here to display labels and checkboxes for all of our colors.
 {colorNames.map((color) => (
 <div key={color}>
 <label htmlFor={color}>
 // We convert lower case color names to human readable title case.
 {color[0].toUpperCase() + color.slice(1)}
 </label>
 // We create a controlled checkbox input element for every color, using the colorState variable that we created earlier to store the state values. 
 <input
 name={color}
 type=”checkbox”
 // For checkboxes we use the checked prop instead of the value prop that we use in text inputs.
 checked={colorState[color]}
 // We create a copy of the colorState object with only our newly checked color value changed.
 onChange={() =>
 setColorState({ …colorState, [color]: !colorState[color] })
 }
 />
 </div>
 ))}
 </div>
// This is the button the user will have to click to submit their search query and render the embedded videos matching their preferences.
 <button
 onClick={() => {
 // We get the checked colors and construct our search query based on them, currently just by joining them on a single space and adding the word “eyeshadow”
 const checkedColors = colorNames
 .filter((color) => colorState[color])
 .map((color) => `”${color}”`);
 window.gapi.client.youtube.search
 .list({
 part: [“snippet”],
 maxResults: 25,
 // If no colors are checked, then checkedColors.length will be 0 (falsy) in which case we will just search for “natural” eyeshadow.
 q: `${
 checkedColors.length ? checkedColors.join(“ “) : “natural”
 } eyeshadow`,
 })
 .then(
 function (response) {
 // Handle the results here (response.result has the parsed body).
 console.log(“Response”, response);
 // Here we save our search results to state so we can map over them below. We only need the response.result.items array so we can discard all of the other metadata in response.
 setSearchResults(response.result.items);
 },
 function (err) {
 console.error(“Execute error”, err);
 }
 );
 }}
 >
 Search
 </button>
 
 // We only show the first 5 results here to improve loading times, but feel free to change this as you please.
 {searchResults.slice(0, 5).map((sr) => (
 <div key={sr.id.videoId}>
 // For each search result, we have an embedded video using the youtube.com/embed url scheme. The iframe needs to be enclosed by a div with a unique key to comply with React guidelines requiring every mapped element to be uniquely identified. 
 <iframe
 title={sr.id.videoId}
 width=”700"
 height=”345"
 src={`https://www.youtube.com/embed/${sr.id.videoId}`}
 ></iframe>
 </div>
 ))}
 </div>
 );
}
export default App;

Используйте npm start для запуска вашего приложения.

К счастью, проекты create-react-app можно легко развернуть на Heroku. Если вы хотите сделать это, сначала установите инструменты командной строки Heroku через homebrew. Затем вы можете создать свое приложение heroku, выполнив эту команду в своем терминале в корневой папке проекта:

heroku create <YOUR-APP-NAME>

Теперь нам просто нужно развернуть его на Heroku, добавив git и зафиксировав любые несохраненные изменения, а затем выполнив эту команду:

git push heroku main

Через несколько минут вы сможете просматривать свое приложение в Интернете по адресу https://<YOUR-APP-NAME>.herokuapp.com!

И это все! Надеюсь, вам будет так же весело, как и мне!

Приведенный выше код находится под лицензией GNU GPLV3. Вы можете узнать больше на https://github.com/trueimpulse/eyeshadow-stackathon