-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chat.tsx
53 lines (49 loc) · 1.62 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 { 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 { MessageList } from "@/Chat/MessageList";
import { Message } from "@/Chat/Message";
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 }).catch((error) => {
console.error("Failed to send message:", error);
});
};
return (
<>
<MessageList messages={messages}>
{messages?.map((message) => (
<Message
key={message._id}
author={message.userId}
authorName={message.author}
viewer={viewer}
>
{message.body}
</Message>
))}
</MessageList>
<div className="border-t">
<form onSubmit={handleSubmit} className="container flex gap-2 py-4">
<Input
value={newMessageText}
onChange={(event) => setNewMessageText(event.target.value)}
placeholder="Write a message…"
/>
<Button type="submit" disabled={newMessageText === ""}>
Send
</Button>
</form>
</div>
</>
);
}