From d71b50ee04f23990c3a364a588cb8cc9e3edfbac Mon Sep 17 00:00:00 2001 From: Somnath Chattaraj Date: Thu, 24 Oct 2024 11:13:15 +0530 Subject: [PATCH] Fix messages allignment --- .../src/components/chatroomui/chatroom.jsx | 114 ++++++++---------- 1 file changed, 51 insertions(+), 63 deletions(-) diff --git a/frontend/src/components/chatroomui/chatroom.jsx b/frontend/src/components/chatroomui/chatroom.jsx index d05e1ee..7f937ae 100644 --- a/frontend/src/components/chatroomui/chatroom.jsx +++ b/frontend/src/components/chatroomui/chatroom.jsx @@ -15,7 +15,6 @@ const Chatroom = () => { const messageEndRef = useRef(null); const [userLookup, setUserLookup] = useState({}); const { loadingUser, userDeatils } = useUser(); - const {users,setUsers} = useState([]); const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket( WEBSOCKET_URL @@ -28,26 +27,22 @@ const Chatroom = () => { withCredentials: true, }); setPrevMsg(response.data); + const roomDetails = await axios.get(`/api/chat/rooms/${roomId}`, { withCredentials: true, }); - const users = roomDetails.data.users; - // Array of users with userId, username, email - console.log(users); - // Create a user lookup map: { userId: username } + const users = roomDetails.data.users; + const lookup = users.reduce((acc, user) => { acc[user.user_id] = user.username; return acc; }, {}); setUserLookup(lookup); - const tosend = { + + sendJsonMessage({ type: "joinRoom", - data: { - userId: userId, - roomId: roomId, - }, - }; - sendJsonMessage(tosend); + data: { userId, roomId }, + }); } catch (error) { console.error("Error fetching chat history:", error); } @@ -55,6 +50,8 @@ const Chatroom = () => { fetchChatHistory(); }, [roomId, userId, sendJsonMessage]); + + // Handle incoming messages from WebSocket useEffect(() => { if (lastJsonMessage !== null) { if (lastJsonMessage.type === "error") { @@ -65,6 +62,7 @@ const Chatroom = () => { ) { const data = lastJsonMessage.data.message; + // Only add message if it is from another user (to prevent duplicates) if (data.senderId !== userId) { setAllMsg((prev) => [ ...prev, @@ -79,7 +77,7 @@ const Chatroom = () => { } }, [lastJsonMessage, roomId, userId]); - // Auto-scroll to the bottom when messages are updated + // Auto-scroll to the bottom when messages update useEffect(() => { if (messageEndRef.current) { messageEndRef.current.scrollIntoView({ behavior: "smooth" }); @@ -89,26 +87,19 @@ const Chatroom = () => { if (loadingUser) { return
Loading...
; } - // if (!userDeatils) { - // return ; - // } - // Submit message function const submit = () => { - const tosend = { + const messageData = { type: "sendMessage", - data: { - roomId: roomId, - userId: userId, - message: myMsg, - }, + data: { roomId, userId, message: myMsg }, }; - sendJsonMessage(tosend); + sendJsonMessage(messageData); + // Add message to local state immediately without waiting for WebSocket confirmation setAllMsg((prev) => [ ...prev, { - senderId: "you", + senderId: userId, message: myMsg, at: new Date().toISOString(), }, @@ -116,7 +107,6 @@ const Chatroom = () => { setMyMsg(""); }; - // Format date const formatDate = (isoString) => { const date = new Date(isoString); return new Intl.DateTimeFormat("en-US", { @@ -135,17 +125,13 @@ const Chatroom = () => { [ReadyState.UNINSTANTIATED]: "Uninstantiated", }[readyState]; - // Combine and sort messages const combinedMessages = [...prevMsg, ...allMsg].sort( (a, b) => new Date(a.at) - new Date(b.at) ); - return (
- - {/* Header */}

Connection Status:{" "} @@ -161,45 +147,49 @@ const Chatroom = () => { Room ID: {roomId || "null"}

- - {/* Messages */} +
- {combinedMessages.length ? ( + {combinedMessages.length ? ( combinedMessages.map((data, index) => (
-
- {/* Show 'You' for the current user, else display the corresponding username */} - {data.senderId === userId ? "You" : userLookup[data.senderId] || data.senderId} +
+
+ {data.senderId === userId ? "You" : userLookup[data.senderId] || data.senderId} +
+ +
+ {data.message} +
+ +
+ Sent at: {formatDate(data.at)} +
+
- -
- {data.message || data.content} -
-
- Sent at: {formatDate(data.at) || formatDate(data.timestamp)} + )) + ) : ( +
No messages yet
+ )} +
-
- )) - ) : ( -
No messages yet
- )} -
-
- - {/* Input Section */} +
{
); - - }; export default Chatroom;