-
Notifications
You must be signed in to change notification settings - Fork 1
/
Chat.tsx
53 lines (49 loc) · 1.66 KB
/
Chat.tsx
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
"use client";
import { Message } from "@/app/product/Chat/Message";
import { MessageList } from "@/app/product/Chat/MessageList";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useMutation, useQuery } from "convex/react";
import { FormEvent, useState } from "react";
import { api } from "../../../convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";
export function Chat({ viewer }: { viewer: Id<"users"> }) {
const [newMessageText, setNewMessageText] = useState("");
const messages = useQuery(api.messages.list);
const sendMessage = useMutation(api.messages.send);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setNewMessageText("");
sendMessage({ body: newMessageText, author: viewer }).catch((error) => {
console.error("Failed to send message:", error);
});
};
return (
<>
<MessageList messages={messages}>
{messages?.map((message) => (
<Message
key={message._id}
authorName={message.author}
authorId={message.userId}
viewerId={viewer}
>
{message.body}
</Message>
))}
</MessageList>
<div className="border-t">
<form onSubmit={handleSubmit} className="flex gap-2 p-4">
<Input
value={newMessageText}
onChange={(event) => setNewMessageText(event.target.value)}
placeholder="Write a message…"
/>
<Button type="submit" disabled={newMessageText === ""}>
Send
</Button>
</form>
</div>
</>
);
}