1
|
|
|
import React, {useEffect, useState} from "react"; |
2
|
|
|
import {Button, Form} from "react-bootstrap"; |
3
|
|
|
import MediaCard from "../components/MediaCard"; |
4
|
|
|
import {MediaResource} from "../interfaces"; |
5
|
|
|
|
6
|
|
|
const pageSize = 10; |
7
|
|
|
|
8
|
|
|
function SearchPage(): JSX.Element { |
9
|
|
|
const [mediaElements, setMediaElements] = useState<MediaResource[]>([]); |
10
|
|
|
const [searchFieldContent, setSearchFieldContent] = useState(""); |
11
|
|
|
const [query, setQuery] = useState(""); |
12
|
|
|
const [startIndex, setStartIndex] = useState(0); |
13
|
|
|
const [isLoading, setIsLoading] = useState(false); |
14
|
|
|
|
15
|
|
|
useEffect(() => { |
16
|
|
|
async function fetchData() { |
17
|
|
|
setIsLoading(true); |
18
|
|
|
const request = await fetch("/api/search", { |
19
|
|
|
method: "POST", |
20
|
|
|
body: JSON.stringify({query: query, startIndex: startIndex, endIndex: startIndex + pageSize}) |
21
|
|
|
}); |
22
|
|
|
|
23
|
|
|
if (request.status === 200) { |
24
|
|
|
const response = await request.json(); |
25
|
|
|
setMediaElements(response.documents === null ? [] : response.documents); |
26
|
|
|
setStartIndex(startIndex + pageSize); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
setIsLoading(false); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
fetchData(); |
33
|
|
|
}, [query]); |
34
|
|
|
|
35
|
|
|
function handleChange(e: React.ChangeEvent<HTMLInputElement>) { |
36
|
|
|
setSearchFieldContent(e.target.value); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
function handleSearch(e: React.FormEvent) { |
40
|
|
|
e.preventDefault(); |
41
|
|
|
setQuery(searchFieldContent); |
42
|
|
|
setStartIndex(0); |
43
|
|
|
setMediaElements([]); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return ( |
47
|
|
|
<React.Fragment> |
48
|
|
|
<form className="top" onSubmit={handleSearch}> |
49
|
|
|
<Form.Control className="m-1" type="text" onChange={handleChange}/> |
50
|
|
|
<Button type="submit" className="m-1">Search</Button> |
51
|
|
|
</form> |
52
|
|
|
|
53
|
|
|
<div className="media-flex-container"> |
54
|
|
|
{mediaElements.map(element => <MediaCard key={element._id.toString()} {...element} />)} |
55
|
|
|
{isLoading && <h1>Loading...</h1>} |
56
|
|
|
</div> |
57
|
|
|
</React.Fragment> |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
export default SearchPage; |
62
|
|
|
|