mj.akbarian
mj.akbarian

Reputation: 71

Perform action on seen/unseen messages with socket.io

What is the best practice to handle seen/unseen messages in a chat room application based on Nodejs/SocketIO/React.

Consider User1 sends a message to a room. If another user has seen that message, notify all users that the state of message has been seen.

In my opinion using message brokers can be the better solution instead socket. I actually think that socket should only handle chat messages that are synchronously. but for seen/unseen status I prefer message brokers that are asynchronous. Are there any solutions or best practice in large scale applications?

Upvotes: 1

Views: 1547

Answers (1)

Cohen
Cohen

Reputation: 2415

It's unclear what you have currently tried, meaning that I can only advise solutions in order to achieve your aim.

To firstly identify that a message was seen, IntersectionObserver is an inbuilt API that detects when an element has entered the viewport, meaning that it is visible, therefore; obviously seen. I have added comments in the code below where you should add a function to call to the server that the message was seen, however, that's up to you to implement.

const observer = new window.IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) {
    // Send a message to the server that the user has viewed the message.
    // Eg. socket.emit('read-message', message.id)
    return
  }
}, {
  root: null,
  threshold: 0.1,
})
observer.observe(document.getElementById(message.id));

Additionally, there's no need to use message broker, as socket.io can handle simple interactions such as this.

You then need to send a message to the server that denotes the specified message ID was seen, then broadcast to every other client that the state was changed, and update it to read - if that's needed.

Upvotes: 1

Related Questions