Skip to content

Commit

Permalink
matbe fixed chat
Browse files Browse the repository at this point in the history
  • Loading branch information
Singh committed Dec 31, 2023
1 parent f29f873 commit acb547f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 16 deletions.
26 changes: 22 additions & 4 deletions frontend/components/Infinite-message-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,19 @@ const InfiniteMessageList: React.FC<InfiniteMessageListProps> = ({
);

const endRef = useRef<HTMLDivElement>(null);
const formRefSend = useRef<HTMLFormElement>(null);
const { ref: topMessageRef, inView } = useInView({ threshold: 0.5 });
const { ref: bottomMessageRef, inView: isBottomInView } = useInView({
threshold: 1,
});
const { execute } = useAction(createMessage);
const { execute } = useAction(createMessage, {
onSuccess: (data) => {
formRefSend.current?.reset();
},
onError: (error) => {
toast.error(error);
},
});

const mergeMessages = useCallback(
(incomingMessages: ExtentedMessage[]) => {
Expand Down Expand Up @@ -104,14 +112,23 @@ const InfiniteMessageList: React.FC<InfiniteMessageListProps> = ({
);

useEffect(() => {
// Establish socket connection and setup event listeners
if (socket && socket.connected) {
toast.info('Socket is connected, setting up listeners');
socket.on(SocketEvent.NewMessage, handleNewMessage);
socket.on(SocketEvent.MessageVoteUpdate, handleNewMessage);
return () => {
} else {
console.log('Socket is not connected yet');
}

// Cleanup event listeners on component unmount or before re-establishing new ones
return () => {
if (socket) {
console.log('Cleaning up listeners');
socket.off(SocketEvent.NewMessage, handleNewMessage);
socket.off(SocketEvent.MessageVoteUpdate, handleNewMessage);
};
}
}
};
}, [socket, handleNewMessage]);
useEffect(() => {
if (isBottomInView && endRef.current && messagesLoaded) {
Expand Down Expand Up @@ -227,6 +244,7 @@ const InfiniteMessageList: React.FC<InfiniteMessageListProps> = ({
</ScrollArea>
{liveSession.isActive && (
<form
ref={formRefSend}
onSubmit={handleMessageSubmit}
className="border-t pt-4 flex items-end"
>
Expand Down
48 changes: 36 additions & 12 deletions frontend/hooks/useSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function useSocket(
const { execute } = useAction(addSessionParticipant);

useEffect(() => {
// Only try to connect if we have the necessary tokens and the session is active
if (
!userSession.user.externalToken ||
!liveSession.isActive ||
Expand All @@ -25,6 +26,11 @@ export function useSocket(
return;
}

// Define the reconnection attempts and delay
const maxReconnectAttempts = 3;
let reconnectAttempts = 0;
const reconnectDelay = 3000; // reconnect after 3 seconds

socketRef.current = io(
process.env.NEXT_PUBLIC_SOCKET_IO_SERVER_URL as string,
{
Expand All @@ -33,34 +39,52 @@ export function useSocket(
token: userSession.user.externalToken,
},
transports: ['websocket'],
reconnectionAttempts: maxReconnectAttempts, // use this for automatic reconnection attempts
reconnectionDelay: reconnectDelay,
}
);

socketRef.current.on('connect', () => {
if (socketRef?.current) {
toast.info('Connected to the session');

socketRef?.current.emit(SocketEvent.JoinSession, liveSession.id);
reconnectAttempts = 0; // reset reconnect attempts on successful connect
if (socketRef.current) {
socketRef.current.emit(SocketEvent.JoinSession, liveSession.id);
execute({
sessionId: liveSession.id,
userId: userSession.user.id!,
});
}
});

const handleReconnect = (reason: any) => {
toast.error(reason || reason.message);
const handleReconnectAttempt = () => {
reconnectAttempts++;
if (reconnectAttempts > maxReconnectAttempts) {
toast.error(
'Failed to reconnect to the session after several attempts.'
);
socketRef.current?.close();
} else {
toast.info(`Attempt ${reconnectAttempts} to reconnect...`);
}
};
socketRef.current.on('disconnect', handleReconnect);
socketRef.current.on('connect_error', handleReconnect);
socketRef.current.on('error', (errorMessage: string) => {
toast.error(errorMessage);

// Register the event for reconnection attempts
socketRef.current.on('reconnect_attempt', handleReconnectAttempt);

// Error handling
const handleError = (error: any) => {
toast.error(
error.message || 'An error occurred with the socket connection.'
);
socketRef.current?.close();
});
};

socketRef.current.on('disconnect', handleError);
socketRef.current.on('connect_error', handleError);
socketRef.current.on('error', handleError);

return () => {
if (socketRef.current?.connected) {
toast.error('Disconnecting from session');
toast.info('Disconnecting from session');
socketRef.current.close();
}
};
Expand Down

0 comments on commit acb547f

Please sign in to comment.