-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.customhook.html
87 lines (75 loc) · 2.33 KB
/
18.customhook.html
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html>
<head>
<title>custom hook</title>
<meta charset="utf-8" />
<style>
body {
font-family: -apple-system, sans-serif;
}
</style>
</head>
<body>
<div id="app"></div>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="react/babel.js"></script>
<script type="text/babel">
const { Fragment, useState, useEffect } = React;
const useDataApi = (initialUrl, initialData) => {
const [data, setData] = useState(initialData);
const [url, setUrl] = useState(initialUrl);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await (await fetch(url)).json();
setData(result);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [url]);
return [{ data, isLoading, isError }, setUrl];
};
function App() {
const [query, setQuery] = useState("react");
const [{ data, isLoading, isError }, doFetch] = useDataApi(
"https://hn.algolia.com/api/v1/search?query=react",
{ hits: [] }
);
return (
<Fragment>
<form
onSubmit={(event) => {
doFetch(`http://hn.algolia.com/api/v1/search?query=${query}`);
event.preventDefault();
}}
>
<input type="text" value={query} onChange={(event) => setQuery(event.target.value)} />
<button type="submit">Search</button>
</form>
{isError && <div>Something went wrong ...</div>}
{isLoading ? (
<div>Loading ...</div>
) : (
<ul>
{data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
)}
</Fragment>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
</body>
</html>