-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.jsx
40 lines (33 loc) · 1.09 KB
/
index.jsx
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
import React, { useState, useEffect } from "react";
import { useChannel } from "@ably-labs/react-hooks";
import { ChatHistory } from "./ChatHistory";
import { SelectAChannel } from "./SelectAChannel";
import { ChatInput } from "./ChatInput";
import "./chat.css";
const Chat = ({ currentChannel }) => {
if (currentChannel === null) {
return <SelectAChannel />;
}
const rewindParameters = "[?rewind=100]";
const channelSubscription = rewindParameters + currentChannel;
const [history, setHistory] = useState([]);
useEffect(() => {
setHistory([]); // Reset history on channel change
}, [currentChannel]);
const [channel, ably] = useChannel(channelSubscription, (message) => {
setHistory((prev) => [...prev.slice(-199), message]);
});
const sendMessage = (messageText) => {
channel.publish("message", { text: messageText });
};
return (
<section className="chat">
<h2>{currentChannel}</h2>
<ul className="messages">
<ChatHistory history={history} />
</ul>
<ChatInput sendMessage={sendMessage} />
</section>
);
};
export default Chat;