generated from lucien/api-template
fix: improved websocket usage
This commit is contained in:
parent
fbf7821320
commit
132b1f3c06
7 changed files with 135 additions and 79 deletions
|
@ -25,17 +25,62 @@ export default function UserPage() {
|
|||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
axios.get(`/api/users/${username}`).then((res) => {
|
||||
setPageUser(res.data);
|
||||
});
|
||||
axios
|
||||
.get(`/api/users/${username}`)
|
||||
.then((res) => {
|
||||
setPageUser(res.data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err.response);
|
||||
});
|
||||
|
||||
axios.get(`/api/users/${username}/lastmessages`).then((res) => {
|
||||
setMessages(res.data);
|
||||
});
|
||||
axios
|
||||
.get(`/api/users/${username}/lastmessages`)
|
||||
.then((res) => {
|
||||
setMessages(res.data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err.response);
|
||||
});
|
||||
}, [username]);
|
||||
|
||||
useEffect(() => {
|
||||
const socket = new WebSocket("/api/ws");
|
||||
|
||||
const id = setInterval(() => {
|
||||
socket.send(JSON.stringify("ping"));
|
||||
}, 10000);
|
||||
|
||||
socket.addEventListener('message', function (event) {
|
||||
const data = JSON.parse(event.data);
|
||||
if ((data.type === "new_message" || data.type === "delete_message") && data.user_id === pageUser?.id) {
|
||||
console.log("new message");
|
||||
axios
|
||||
.get(`/api/users/${username}/lastmessages`)
|
||||
.then((res) => {
|
||||
setMessages(res.data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err.response);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
socket.close();
|
||||
};
|
||||
}, [pageUser]);
|
||||
|
||||
if (!pageUser) {
|
||||
return <div>Loading...</div>;
|
||||
return (
|
||||
<div className="user-page">
|
||||
<TopBar user={user} />
|
||||
<div className="user">
|
||||
<h2>Loading...</h2>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue