added files in git
This commit is contained in:
44
src/hooks/useChatSocket.js
Normal file
44
src/hooks/useChatSocket.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useEffect, useRef, useState, useCallback } from "react";
|
||||
import { Client } from "@stomp/stompjs";
|
||||
import SockJS from "sockjs-client";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
export function useChatSocket(chatId, onMessage) {
|
||||
const clientRef = useRef(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chatId) return;
|
||||
|
||||
const token = localStorage.getItem("token");
|
||||
const socket = new SockJS(`${API_URL}/ws?token=${token}`);
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => socket,
|
||||
reconnectDelay: 3000,
|
||||
onConnect: () => {
|
||||
setConnected(true);
|
||||
client.subscribe(`/topic/chat/${chatId}`, (msg) => {
|
||||
const body = JSON.parse(msg.body);
|
||||
onMessage(body);
|
||||
});
|
||||
},
|
||||
onDisconnect: () => setConnected(false),
|
||||
});
|
||||
|
||||
client.activate();
|
||||
clientRef.current = client;
|
||||
|
||||
return () => client.deactivate();
|
||||
}, [chatId, onMessage]);
|
||||
|
||||
const sendMessage = useCallback((content) => {
|
||||
if (!clientRef.current?.connected) return;
|
||||
clientRef.current.publish({
|
||||
destination: "/app/chat.send",
|
||||
body: JSON.stringify({ chatId, content }),
|
||||
});
|
||||
}, [chatId]);
|
||||
|
||||
return { connected, sendMessage };
|
||||
}
|
||||
Reference in New Issue
Block a user