-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path'
63 lines (61 loc) · 2.37 KB
/
'
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
54
55
56
57
58
59
60
61
62
63
import { useContext, useEffect, useState } from "react";
import ChatArea from "./chatArea/chatArea";
import SideBar from "./roomList";
import { IMessage } from "../../types/IMessage";
import style from "./mainPage.module.css";
import { get } from "../../util/fetch";
import { API_URL } from "../../constants";
import { getAccessToken } from "../../util/getAccessToken";
import { socket } from "../../context/socket";
import { RoomContext } from "../../context/room/roomContext";
const MainPage = () => {
const { rooms, updated, setUpdated, focus, setFocus } = useContext(RoomContext)
const [msgs, setMsgs] = useState({} as { [key: string]: IMessage[] });
useEffect(() => {
socket.on("error", (error: unknown) => {
console.log(error);
});
socket.on("incomingMessage", (msg: IMessage) => {
setMsgs((prev) => {
return { ...prev, [msg.roomId]: [...(prev[msg.roomId] ?? []), msg] };
});
});
socket.on("updateName", () => ({ id, newName }: { id: string, newName: string }) => {
console.log(newName)
// setRooms(prev => {
// if (prev[id] != undefined) {
// return { ...prev, [id]: { ...prev[id], name: newName } }
// } else return prev;
// })
})
return () => {
socket.off("incomingMessage");
socket.off("error");
socket.off("updateName");
};
}, []);
useEffect(() => {
if (focus == undefined) return;
if (!updated[`${focus}`]) {
getAccessToken()
.then((token) =>
get<IMessage[]>(`${API_URL}/room/getroommessages/${focus}`, {
headers: { Authorization: `Bearer ${token}` },
})
)
.then(([data, err]) => {
if (!err) {
setMsgs((prev) => ({ ...prev, [`${focus}`]: data }));
setUpdated((prev) => ({ ...prev, [`${focus}`]: true }));
}
});
}
}, [focus, updated, setUpdated]);
return (
<div className={style.container}>
<SideBar setFocus={setFocus} focus={focus} />
<ChatArea room={rooms[`${focus}`]} messages={msgs[focus ?? ""] ?? []} />
</div>
);
};
export default MainPage;