-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
88 lines (77 loc) · 2.4 KB
/
index.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
88
<!DOCTYPE html>
<html>
<head>
<title>React Test</title>
<script
crossorigin
src="https://unpkg.com/react@18/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script
src="https://code.jquery.com/jquery-3.6.4.min.js"
integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
crossorigin="anonymous"
></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useRef } = React;
const URL = 'https://api.agify.io';
const nameStore = {};
const fetchData = (url) => {
return new Promise((resolve, reject) => {
$.get(url, (data) => resolve(data)).fail((er) => reject(er));
});
};
const fetchByName = async (name, apiUrl = URL) => {
const url = `${apiUrl}?name=${name}`;
return await fetchData(url);
};
const getAge = async (name) => {
if (nameStore[name.toLowerCase()]) {
return nameStore[name.toLowerCase()].age;
}
const data = await fetchByName(name);
const age = data.age ? data.age : 0;
nameStore[name.toLowerCase()] = { age };
return age;
};
const Form = ({ handleSubmit }) => {
const inputRef = useRef();
return (
<form onSubmit={(ev) => handleSubmit(ev, inputRef.current.value)}>
<label>
Please enter a name: <pre></pre>
<input name="nameInput" id="nameInput" ref={inputRef} />
</label>
<button>Submit</button>
</form>
);
};
const AgeDisplay = ({ age }) => {
return <div>The estimated age is {age} </div>;
};
const App = () => {
const [age, setAge] = useState(0);
const handleSubmit = async (ev, name) => {
ev.preventDefault();
const age = await getAge(name);
setAge(age);
};
return (
<div>
<h1>Estimate the age based on a first name</h1>
<Form handleSubmit={handleSubmit} />
{age !== 0 && <AgeDisplay age={age} />}
</div>
);
};
ReactDOM.render(<App />, document.querySelector('#root'));
</script>
</body>
</html>