-
Notifications
You must be signed in to change notification settings - Fork 2
/
Search.js
50 lines (45 loc) · 1.28 KB
/
Search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import React from 'react';
import Videos from '../components/Videos';
function Search() {
const [searchTerm, setSearchTerm] = React.useState('');
const [videos, setVideos] = React.useState(null);
const [warning, setWarning] = React.useState(false);
const apiKey = process.env.NEXT_PUBLIC_YOUTUBE_API_KEY;
const handleSubmit = (event) => {
event.preventDefault();
if (!searchTerm) {
setWarning(true);
return;
}
let url = `https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q=${searchTerm}&key=${apiKey}`;
fetch(url)
.then((res) => res.json())
.then((data) => {
setVideos(data);
setSearchTerm(null);
});
event.target.reset();
};
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="search"></label>
<input
type="text"
aria-label="Search videos"
placeholder="Search videos"
name="search"
value={searchTerm}
onChange={(e) => {
setWarning(false);
setSearchTerm(e.target.value);
}}
/>
<button type="submit">Search</button>
</form>
{warning && <p>Please insert a term</p>}
{videos && <Videos data={videos} />}
</>
);
}
export default Search;