'Listening on client side using Socket.on not working

when I am trying to send it to particular room id using socket.to(roomId).emit('msgToClient', data) my client side on react not listening any messages but if I use socket.emit('msgToClient', data)its working fine, I am adding my client side and server side code below.

useChat hook in react client to receive a server message

const useChat = (roomId) => {
  const [messages, setMessages] = useState([]); // Sent and received messages
  const socketRef = useRef();

  useEffect(() => {
    
    // Creates a WebSocket connection
    socketRef.current = io(SOCKET_SERVER_URL, {
        query: { roomId },  transports: ['websocket'] });
    
    // Listens for incoming messages
    socketRef.current.on('msgToClient', (message) => {
      const incomingMessage = {
        ...message,
        ownedByCurrentUser: message.senderId === socketRef.current.id,
      };
      setMessages((messages) => [...messages, incomingMessage]);
    });
    
    // Destroys the socket reference
    // when the connection is closed
    return () => {
      socketRef.current.disconnect();
    };
  }, [roomId]);

  return { messages, sendMessage, joinRoom };
};

export default useChat;

message.gateway in NestJs to send it to client

@WebSocketGateway()
export class MessageGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() socket: Socket;

  private logger: Logger = new Logger('MessageGateway');

  @SubscribeMessage('msgToServer')
  public handleMessage(client: Socket, payload: any): void {
    this.socket.to(client.handshake.query.roomId).emit('msgToClient', payload);
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source