add: improved the frontend and the backend by adding websockets

This commit is contained in:
Lukian 2025-04-07 22:46:04 +02:00
parent ecf7b61aca
commit fbf7821320
18 changed files with 255 additions and 65 deletions

View file

@ -12,6 +12,7 @@ export default function Home() {
const [channels, setChannels] = useState<RecentChannels>();
const [messages , setMessages] = useState<Messages>();
const [searchedChannels, setSearchedChannels] = useState<Channels>([]);
const [newChannels, setNewChannels] = useState<Channels>([]);
const [search, setSearch] = useState<string>("");
useEffect(() => {
@ -45,27 +46,60 @@ export default function Home() {
})
.catch((err) => {
console.error(err.response)
}
)
})
axios
.get("/api/newchannels")
.then((res) => {
setNewChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
}, [])
useEffect(() => {
const id = setInterval(() => {
axios
.get("/api/activechannels").then((res) => {
setChannels(res.data)
}
)
const socket = new WebSocket("/api/channels");
axios
.get("/api/lastmessages").then((res) => {
setMessages(res.data)
}
)
socket.addEventListener('message', function (event) {
if (event.data === "new_message" || event.data === "delete_message") {
axios
.get("/api/lastmessages")
.then((res) => {
setMessages(res.data)
})
.catch((err) => {
console.error(err.response)
})
}, 2000)
axios
.get("/api/activechannels")
.then((res) => {
setChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
} else if (event.data === "new_channel") {
axios
.get("/api/activechannels")
.then((res) => {
setChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
return () => { clearInterval(id) }
axios
.get("/api/newchannels")
.then((res) => {
setNewChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
}
});
}, [])
useEffect(() => {
@ -125,6 +159,16 @@ export default function Home() {
))}
</ul>
</div>
<div className="channels-new">
<h3>Last created channels</h3>
<ul>
{newChannels?.map((channel) => (
<li key={channel.id}>
<Link to={`/c/${channel.name}`}>{channel.name}</Link>
</li>
))}
</ul>
</div>
<div className="channels-search">
<h3>Search channels</h3>
<input