forked from replicate/getting-started-nextjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (80 loc) · 2.31 KB
/
index.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
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
89
import { useState } from "react";
import Head from "next/head";
import Image from "next/image";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export default function Home() {
const [prediction, setPrediction] = useState(null);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("/api/predictions", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: e.target.prompt.value,
}),
});
let prediction = await response.json();
if (response.status !== 201) {
setError(prediction.detail);
return;
}
setPrediction(prediction);
while (
prediction.status !== "succeeded" &&
prediction.status !== "failed"
) {
await sleep(1000);
const response = await fetch("/api/predictions/" + prediction.id);
prediction = await response.json();
if (response.status !== 200) {
setError(prediction.detail);
return;
}
console.log({ prediction });
setPrediction(prediction);
}
};
return (
<div className="container max-w-2xl mx-auto p-5">
<Head>
<title>Replicate + Next.js</title>
</Head>
<h1 className="py-6 text-center font-bold text-2xl">
Dream something with{" "}
<a href="https://replicate.com/stability-ai/sdxl?utm_source=project&utm_project=getting-started">
SDXL
</a>
</h1>
<form className="w-full flex" onSubmit={handleSubmit}>
<input
type="text"
className="flex-grow"
name="prompt"
placeholder="Enter a prompt to display an image"
/>
<button className="button" type="submit">
Go!
</button>
</form>
{error && <div>{error}</div>}
{prediction && (
<>
{prediction.output && (
<div className="image-wrapper mt-5">
<Image
fill
src={prediction.output[prediction.output.length - 1]}
alt="output"
sizes="100vw"
/>
</div>
)}
<p className="py-3 text-sm opacity-50">status: {prediction.status}</p>
</>
)}
</div>
);
}