2022-03-31 00:15:20 -04:00
|
|
|
import { useState, useContext, useEffect, useRef } from 'react';
|
|
|
|
import { AuthContext } from './auth_context';
|
|
|
|
import { io } from 'socket.io-client';
|
|
|
|
|
2022-04-01 18:04:00 -04:00
|
|
|
export const useChat = (chatRoom) => {
|
2022-03-31 00:15:20 -04:00
|
|
|
const [messages, setMessages] = useState([]);
|
2022-04-01 18:04:00 -04:00
|
|
|
const [connections, setConnections] = useState([]);
|
2022-04-01 18:31:24 -04:00
|
|
|
const [active, setActive] = useState(true);
|
2022-03-31 00:15:20 -04:00
|
|
|
const messageRef = useRef([]);
|
|
|
|
const [socket, setSocket] = useState({});
|
|
|
|
const [authToken] = useContext(AuthContext);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (chatRoom?.id) {
|
|
|
|
const socket = io({
|
|
|
|
query: {
|
|
|
|
chatRoomId: chatRoom.id,
|
|
|
|
},
|
|
|
|
auth: {
|
|
|
|
token: authToken,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
socket.on('connect', () => {
|
|
|
|
setSocket(socket);
|
|
|
|
});
|
|
|
|
socket.on('new-message', (message) => {
|
|
|
|
messageRef.current.push(message);
|
|
|
|
setMessages([...messageRef.current]);
|
|
|
|
});
|
2022-04-01 18:04:00 -04:00
|
|
|
socket.on('userlist', ({ users }) => {
|
2022-04-01 18:31:24 -04:00
|
|
|
setConnections([...users]);
|
|
|
|
});
|
|
|
|
socket.on('inactive', (id) => {
|
|
|
|
setActive(false);
|
2022-04-01 18:04:00 -04:00
|
|
|
});
|
2022-03-31 00:15:20 -04:00
|
|
|
return () => {
|
|
|
|
socket.off('new-message');
|
|
|
|
socket.close();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}, [chatRoom]);
|
|
|
|
|
|
|
|
const sendMessage = (message) => {
|
|
|
|
if (socket?.emit) {
|
|
|
|
socket.emit('message', message);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-04-01 18:31:24 -04:00
|
|
|
return [active, connections, messages, sendMessage];
|
2022-03-31 00:15:20 -04:00
|
|
|
};
|