fixed code v2

This commit is contained in:
SlimusMinus
2026-08-12 00:38:04 +03:00
parent fe3c91446a
commit e45c9326ed
19 changed files with 233 additions and 124 deletions

View File

@@ -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);
}