HazeTV
Available Scripts
In the project directory, you can run:
npm start
Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.
The page will reload if you make edits.
You will also see any lint errors in the console.
npm run build
Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.
Your app is ready to be deployed!
Quando questo comando viene eseguito viene creata la cartella build/ e al suo interno vengono messi i file per la nostra single page application
Axios
https://github.com/axios/axios
prima di tutto importare axios nel file
import axios from 'axios';
// nel link è cosi: const axios = require('axios');
// sono equivalenti ma meglio quello sopra
Richiesta get con axios
richiesta get con axios
axios.get('url', {
// Configuration Object
// Struttura spiegata dopo
}
})
.then(function (response) {
console.log(response);
// Gestisco risposta
// Struttura spiegata dopo
})
.catch(function (error) {
console.log(error);
// Gestisco eventuali errori HTTP
// Struttura spiegata dopo
})
esempio base: le risposte sono visibili nella console degli strumenti di sviluppo (CTRL + SHIFT + I)
axios.get('https://jsonplaceholder.typicode.com/users',
{
id: 1
})
.then(function (response) {
console.log(response);
console.info(response.data);
})
.catch(function (error) {
console.log(error);
});
Il codice sopra è ok, ma nella prossima versione gli errori di axios vengono gestiti nel then() lasciando cosi al catch() i bug del codice javascript:
axios.get('https://jsonplaceholder.typicode.com/users',
{
id: 1
})
.then(
response => { // notazione moderna javascript per indicare function(response){}
// function(response){} == response => {}
console.log(response);
console.info(response.data);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
console.error(error);
}
);
Config Object
In questo oggetto andiamo a definire particolari tipi di configurazione.
Nelle righe dove c'è //default li abbiamo dei parametri predefiniti che permettono gia ad axios di funzionare, possono essere sovrascritti nell'oggetto che passiamo ad axios.
Di norma le uniche proprietà che andremo a definire nell'oggetto saranno params: {} e data:{} rispettivamente per GET e POST.
params:{
id: 1,
name: 'Tiziano'
}
è l'equivalente di: ?id=1&name=tiziano
mentre data:{} sarà riempito con l'oggetto da passare al POST
Quindi in generale axios.get(url,{}) con
{} ==
{
params: {
id: 1,
name: 'Tiziano',
key: 'value'
}
}
Response Object
Dopo ogni axios.get(url,{}) c'è un .then() all'interno di questo then viene definito un parametro chiamato per convenzione response
response sarà un oggetto strutturato in questo modo:
response: {
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
Error object
in generale error.message e error.response.status sono sufficienti.
YouTube API
L'API key è AIzaSyBbuSz5f4wzfVJzHZpDv_UJcM8WZYH4YmE Può essere trovata nel file apikey.
In /videos la durata del video è in formato ISO 8601 con i moduli moment e moment-duration-format possiamo convertilo in formato minuti:secondi (mm:ss)
| ### | ### |
|---|---|
| contentDetails.duration | The length of the video. The property value is an ISO 8601 duration. For example, for a video that is at least one minute long and less than one hour long, the duration is in the format PT#M#S, in which the letters PT indicate that the value specifies a period of time, and the letters M and S refer to length in minutes and seconds, respectively. The # characters preceding the M and S letters are both integers that specify the number of minutes (or seconds) of the video. For example, a value of PT15M33S indicates that the video is 15 minutes and 33 seconds long. If the video is at least one hour long, the duration is in the format PT#H#M#S, in which the # preceding the letter H specifies the length of the video in hours and all of the other details are the same as described above. If the video is at least one day long, the letters P and T are separated, and the value's format is P#DT#H#M#S. Please refer to the ISO 8601 specification for complete details. |
function moment(duration) {
const moment = require("moment");
const momentDurationFormatSetup = require("moment-duration-format");
return moment.duration(duration).format('hh:mm:ss');
}
axios.get('https://www.googleapis.com/youtube/v3/commentThreads',{
params: {
'part': 'snippet',
'videoId': videoId, // variabile con id video
'order': 'relevance',
'key': 'AIzaSyBbuSz5f4wzfVJzHZpDv_UJcM8WZYH4YmE'
}
})
axios.get('https://www.googleapis.com/youtube/v3/videos', {
params: {
'part': 'snippet,contentDetails,statistics,topicDetails',
'id': videoId, // variabile con id video
'key': 'AIzaSyBbuSz5f4wzfVJzHZpDv_UJcM8WZYH4YmE'
}
})
React Bootstrap
import 'bootstrap/dist/css/bootstrap.css';
Il css di bootstrap va importato una volta sola nel componente che racchiude tutta la logica dell'applicazione, infatti qui è importato solamente in App.js.
React stuff
awesome-react --> lista di link su react.
YouTube video player
From react-youtube README:
Usage
<YouTube
videoId={string} // defaults -> null
id={string} // defaults -> null
className={string} // defaults -> null
containerClassName={string} // defaults -> ''
opts={obj} // defaults -> {}
onReady={func} // defaults -> noop
onPlay={func} // defaults -> noop
onPause={func} // defaults -> noop
onEnd={func} // defaults -> noop
onError={func} // defaults -> noop
onStateChange={func} // defaults -> noop
onPlaybackRateChange={func} // defaults -> noop
onPlaybackQualityChange={func} // defaults -> noop
/>
For convenience it is also possible to access the PlayerState constants through react-youtube:
YouTube.PlayerState contains the values that are used by the YouTube IFrame Player API.
Example
import React from 'react';
import YouTube from 'react-youtube';
class Example extends React.Component {
render() {
const opts = {
height: '390',
width: '640',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1
}
};
return (
<YouTube
videoId="2g811Eo7K8U"
opts={opts}
onReady={this._onReady}
/>
);
}
_onReady(event) {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
}
Controlling the player
You can access & control the player in a way similar to the official api:
The component will pass an event object as the sole argument to each of the event handler props. The event object has the following properties:
- The event's
targetidentifies the video player that corresponds to the event.- The event's
dataspecifies a value relevant to the event. Note that theonReadyevent does not specify adataproperty.