fixed code
This commit is contained in:
@@ -22,7 +22,6 @@ export function useChatSocket(chatId, onMessage) {
|
||||
webSocketFactory: () => new SockJS(`${API_URL}/ws`),
|
||||
reconnectDelay: 3000,
|
||||
beforeConnect: async () => {
|
||||
// На каждую попытку коннекта — свежий токен из localStorage
|
||||
client.connectHeaders = {
|
||||
Authorization: `Bearer ${getAccessToken()}`,
|
||||
};
|
||||
@@ -30,13 +29,16 @@ export function useChatSocket(chatId, onMessage) {
|
||||
onConnect: () => {
|
||||
setConnected(true);
|
||||
client.subscribe(`/topic/chat/${chatId}`, (msg) => {
|
||||
const body = JSON.parse(msg.body);
|
||||
onMessageRef.current(body);
|
||||
try {
|
||||
const body = JSON.parse(msg.body);
|
||||
onMessageRef.current(body);
|
||||
} catch (e) {
|
||||
console.error("Failed to parse chat message:", e);
|
||||
}
|
||||
});
|
||||
},
|
||||
onDisconnect: () => setConnected(false),
|
||||
onStompError: async (frame) => {
|
||||
// Если сервер отклонил CONNECT из-за протухшего токена — пробуем обновить и переподключиться
|
||||
if (frame.headers?.message?.includes("Unauthorized")) {
|
||||
try {
|
||||
await refreshAccessToken();
|
||||
@@ -53,12 +55,14 @@ export function useChatSocket(chatId, onMessage) {
|
||||
return () => client.deactivate();
|
||||
}, [chatId]);
|
||||
|
||||
/** @returns {boolean} true если сообщение реально ушло в сокет, false если соединения нет */
|
||||
const sendMessage = useCallback((content) => {
|
||||
if (!clientRef.current?.connected) return;
|
||||
if (!clientRef.current?.connected) return false;
|
||||
clientRef.current.publish({
|
||||
destination: "/app/chat.send",
|
||||
body: JSON.stringify({ chatId, content }),
|
||||
});
|
||||
return true;
|
||||
}, [chatId]);
|
||||
|
||||
return { connected, sendMessage };
|
||||
|
||||
Reference in New Issue
Block a user