I am making a web app where i want to show online/offline status of user. For that i need to listen to close and open events of websocket.
const ws = new WebSocket('ws_url', 'token');
ws.onclose = (e) => {
const data = {
type: "offline",
userId: "someid"
}
ws.send(JSON.stringify(data))
}
2
Answers
Using useEffect you can pass the functions on component destroy, just use "return" isnide https://react.dev/reference/react/useEffect#usage
• You have create a function first to handle the
WebSocket
close event and send your data. You already have this part in your code:• you can use the
beforeunload
event to call this function