added files in git
This commit is contained in:
35
src/hooks/useUnreadSocket.js
Normal file
35
src/hooks/useUnreadSocket.js
Normal file
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Client } from "@stomp/stompjs";
|
||||
import SockJS from "sockjs-client";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { useUnread } from "../context/UnreadContext";
|
||||
import { getActiveChatId } from "../stores/activeChatStore";
|
||||
|
||||
export function useUnreadSocket(userId) {
|
||||
const { setChatUnread } = useUnread();
|
||||
const clientRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId) return;
|
||||
|
||||
const token = localStorage.getItem("token");
|
||||
const socket = new SockJS(`${API_URL}/ws?token=${token}`);
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => socket,
|
||||
reconnectDelay: 3000,
|
||||
onConnect: () => {
|
||||
client.subscribe(`/topic/user/${userId}/unread`, (msg) => {
|
||||
const body = JSON.parse(msg.body);
|
||||
if (body.chatId === getActiveChatId()) return;
|
||||
setChatUnread(body.chatId, body.unreadCount);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
client.activate();
|
||||
clientRef.current = client;
|
||||
|
||||
return () => client.deactivate();
|
||||
}, [userId, setChatUnread]);
|
||||
}
|
||||
Reference in New Issue
Block a user