Skip to content
Permalink
Newer
Older
100644 58 lines (52 sloc) 1.54 KB
January 28, 2022 11:45
1
import Head from "next/head";
2
import { useState } from "react";
3
import styles from "./index.module.css";
4
5
export default function Home() {
6
const [animalInput, setAnimalInput] = useState("");
7
const [result, setResult] = useState();
8
9
async function onSubmit(event) {
10
event.preventDefault();
December 23, 2022 17:30
11
try {
12
const response = await fetch("/api/generate", {
13
method: "POST",
14
headers: {
15
"Content-Type": "application/json",
16
},
17
body: JSON.stringify({ animal: animalInput }),
18
});
19
20
const data = await response.json();
21
if (response.status !== 200) {
22
throw data.error || new Error(`Request failed with status ${response.status}`);
23
}
24
25
setResult(data.result);
26
setAnimalInput("");
27
} catch(error) {
28
// Consider implementing your own error handling logic here
29
console.error(error);
30
alert(error.message);
31
}
January 28, 2022 11:45
32
}
33
34
return (
35
<div>
36
<Head>
37
<title>OpenAI Quickstart</title>
38
<link rel="icon" href="/dog.png" />
39
</Head>
40
41
<main className={styles.main}>
42
<img src="/dog.png" className={styles.icon} />
43
<h3>Name my pet</h3>
44
<form onSubmit={onSubmit}>
45
<input
46
type="text"
47
name="animal"
48
placeholder="Enter an animal"
49
value={animalInput}
50
onChange={(e) => setAnimalInput(e.target.value)}
51
/>
52
<input type="submit" value="Generate names" />
53
</form>
54
<div className={styles.result}>{result}</div>
55
</main>
56
</div>
57
);
58
}