Open your root page and replace it's contents with the following:
export default function ChatPage() {
return <div>Hello, world.</div>;
}
Mark the page as a client component.
"use client"
export default function ChatPage() {
return <div>Hello, world.</div>;
}
Note: we are marking the page as a client component because we will be using hooks and interactivity.
Import and call useChat
.
"use client";
import { useChat } from "ai/react";
export default function ChatPage() {
const { } = useChat();
return <div>Hello, world.</div>;
}
Destructure messages
from useChat
and then iterate over them in the UI.
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages } = useChat();
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.role === "user" ? "User: " : "AI: "}
{m.content}
</div>
))}
</div>
);
}
Destructure input
, handleInputChange
, and handleSubmit
from useChat
. Render a form and use the newly destructured items to handle the state.
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.role === "user" ? "User: " : "AI: "}
{m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
placeholder="Say something..."
onChange={handleInputChange}
/>
</form>
</div>
);
}
Done! Run the dev server.