Home > Blockchain >  socket.io - Messages stored in db are being rendered twice
socket.io - Messages stored in db are being rendered twice

Time:10-07

I am building a chat rooms app in which i'm storing all messages in the database. When user joins same room again, app renders all previous messages from db. but I don't know why all those messages are being printed twice.

  • on Server side

when user tries to join a room it checks if the room exist in db, if not it creates one. and if yes it sends the all the previous messages back to room

     //Join -room

      socket.on('join-room', async (room) => {
          socket.join(room);

          let roomInDB = await Room.findOne({ name: room });
          if (roomInDB === null) {
              io.emit('err', { message: "Creating New Room!" })
              let newRoom = new Room({ name: room })
              await newRoom.save();
          } else {
              Room.findOne({ name: room }).populate('chats').exec((err, chats) => {
                  io.to(room).emit('room_data', chats);
              })
          }
     })
  • On client side

I'm using a displayMessage function to render message in the room.

function displayMessage(messageData, senderClass) {
    // message, sender, time

    const msg_box = document.getElementById("messages");
    const { sender, time, message } = messageData;
    let card = document.createElement("div");
    card.classList.add(senderClass, 'msg_card');

    if (senderClass === 'sent') {
        card.innerHTML = `
        <div class="msg_text">
         ${message}
        </div>
        <div class="time">${time}</div>
        `
    } else {
        card.innerHTML = `
        <div class="msg_text">
        <span class="sent_by">${sender.username}</span> - ${message}
        </div>
        <div class="time">${time}</div>
        `
    }

    msg_box.appendChild(card);
}

So, when user joins a room socket io sends previous messages back, and using displayMessage function I'm rendering those messages in the room but for some reason it's happening twice.

enter image description here

I've tried console loggin when rendering these messages, but it logs correct number of messages and not twice.

CodePudding user response:

I highly recommend that you isolate which side the bug is in by testing a call to the server while taking the client out of the picture. You can do this by using Postman, which now has SocketIO support. If you emit the event that joins a user into a room to the server once and get duplicate messages back, then the issue is on the server side. Otherwise, perhaps you are calling the rendering twice on the client side.

  • Related