|
| 1 | +import { useChat } from "ai/react"; |
| 2 | +import { useState } from "react"; |
| 3 | + |
| 4 | +type ChatProps = { |
| 5 | + id: string; |
| 6 | +}; |
| 7 | + |
| 8 | +export default function Chat(props: ChatProps) { |
| 9 | + const { input, handleInputChange, setInput } = useChat(); |
| 10 | + const [messages, setMessages] = useState<{ role: string; content: string }[]>( |
| 11 | + [] |
| 12 | + ); |
| 13 | + |
| 14 | + const handleSubmit = async (e: React.FormEvent) => { |
| 15 | + e.preventDefault(); |
| 16 | + |
| 17 | + setMessages((prevMessages) => [ |
| 18 | + ...prevMessages, |
| 19 | + { role: "user", content: input }, |
| 20 | + ]); |
| 21 | + const currentInput = input; |
| 22 | + setInput(""); |
| 23 | + |
| 24 | + const response = await fetch(`/api`, { |
| 25 | + method: "POST", |
| 26 | + headers: { |
| 27 | + "Content-Type": "application/json", |
| 28 | + }, |
| 29 | + body: JSON.stringify({ |
| 30 | + messages: [{ role: "user", content: currentInput }], |
| 31 | + }), |
| 32 | + }); |
| 33 | + |
| 34 | + if (!response.ok) { |
| 35 | + console.error("Failed to send message"); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + const data = await response.text(); |
| 40 | + |
| 41 | + if (data) { |
| 42 | + setMessages((prevMessages) => [ |
| 43 | + ...prevMessages, |
| 44 | + { role: "assistant", content: data }, |
| 45 | + ]); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + return ( |
| 50 | + <> |
| 51 | + {messages.map((message) => ( |
| 52 | + <div key={message.id}> |
| 53 | + {message.role === "user" ? "User: " : "AI: "} |
| 54 | + {message.content} |
| 55 | + </div> |
| 56 | + ))} |
| 57 | + |
| 58 | + <form onSubmit={handleSubmit}> |
| 59 | + <input name="prompt" value={input} onChange={handleInputChange} /> |
| 60 | + <button type="submit">Submit</button> |
| 61 | + </form> |
| 62 | + </> |
| 63 | + ); |
| 64 | +} |
0 commit comments