Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Last active December 30, 2022 19:49
Show Gist options
  • Save JenniferFuBook/810053d5b563705b7dd4f1d4ef83ae3b to your computer and use it in GitHub Desktop.
Save JenniferFuBook/810053d5b563705b7dd4f1d4ef83ae3b to your computer and use it in GitHub Desktop.
import React from 'react';
import styles from '../styles/Home.module.css';
const IMAGE_COUNT = 10;
const IMAGE_SIZE = 1024;
export default function Home() {
const [value, setValue] = React.useState<string>('');
const [prompt, setPrompt] = React.useState<string>('');
const [imageIndex, setImageIndex] = React.useState<number>(0);
const [images, setImages] = React.useState<string[]>([]);
const handleInput = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
}, []);
const handleKeyDown = React.useCallback(
async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
setPrompt(value);
setImageIndex(0);
setImages([]);
const response = await fetch('/api/hello', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: value,
n: IMAGE_COUNT,
size: `${IMAGE_SIZE}x${IMAGE_SIZE}`
}),
});
const data = await response.json();
setValue('');
setImages(data.result.map((image: {url: string}) => image.url));
}
}, [value]);
const handleNextImage = React.useCallback(() => {
setImageIndex((imageIndex + 1) % IMAGE_COUNT);
}, [imageIndex]);
return (
<main className={styles.main}>
<div>Please type your prompt</div>
<input value={value} onChange={handleInput} onKeyDown={handleKeyDown} />
<div>Prompt: {prompt}</div>
<button onClick={handleNextImage}>Click to view the next image > </button>
{images.length === 0? <div>Loading...</div> :
<iframe
src={images[imageIndex]}
width={IMAGE_SIZE}
height={IMAGE_SIZE}
/>}
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment