fixed code v2
This commit is contained in:
@@ -1,47 +1,19 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Client } from "@stomp/stompjs";
|
||||
import SockJS from "sockjs-client";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { useCallback } from "react";
|
||||
import { useStompClient, parseStompMessage } from "./useStompClient";
|
||||
import { useUnread } from "../context/UnreadContext";
|
||||
import { getActiveChatId } from "../stores/activeChatStore";
|
||||
import { getAccessToken, refreshAccessToken } from "../api/apiClient";
|
||||
|
||||
export function useUnreadSocket(userId) {
|
||||
const { setChatUnread } = useUnread();
|
||||
const clientRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId) return;
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => new SockJS(`${API_URL}/ws`),
|
||||
reconnectDelay: 3000,
|
||||
beforeConnect: () => {
|
||||
client.connectHeaders = {
|
||||
Authorization: `Bearer ${getAccessToken()}`,
|
||||
};
|
||||
},
|
||||
onConnect: () => {
|
||||
client.subscribe(`/topic/user/${userId}/unread`, (msg) => {
|
||||
const body = JSON.parse(msg.body);
|
||||
if (body.chatId === getActiveChatId()) return;
|
||||
setChatUnread(body.chatId, body.unreadCount);
|
||||
});
|
||||
},
|
||||
onStompError: async (frame) => {
|
||||
if (frame.headers?.message?.includes("Unauthorized")) {
|
||||
try {
|
||||
await refreshAccessToken();
|
||||
} catch {
|
||||
// refresh не удался — общий логин-флоу разберётся при следующем apiFetch
|
||||
}
|
||||
}
|
||||
},
|
||||
const handleConnect = useCallback((client) => {
|
||||
client.subscribe(`/topic/user/${userId}/unread`, (msg) => {
|
||||
parseStompMessage(msg, (body) => {
|
||||
if (String(body.chatId) === getActiveChatId()) return;
|
||||
setChatUnread(body.chatId, body.unreadCount);
|
||||
});
|
||||
});
|
||||
|
||||
client.activate();
|
||||
clientRef.current = client;
|
||||
|
||||
return () => client.deactivate();
|
||||
}, [userId, setChatUnread]);
|
||||
|
||||
useStompClient(!!userId, handleConnect);
|
||||
}
|
||||
Reference in New Issue
Block a user