I am working on socket for chatting. Here is my socket code in nodejs file which is working well.
The outer socket io.emit
working good and emits the message to all the users which are connected to that conversationId
.
But the socket.broadcast.emit
(when user uses the app) which I am using to notify user, emits(socket.broadcast.emit
) events multiple times. Why this is happening? Am I completely missing the socket approach.
socket.on('sendMessage', async(action2) => {
try {
action2.author = socket.decoded.id
action2.readBy = [socket.decoded.id]
action2.deliveredTo = [socket.decoded.id]
const createMessage = await Message.create(action2)
const sender = await User.findOne({ _id: socket.decoded.id }, { firstName: 1 })
const memebers = //some api call to get members
const promises = members.map(async(member) => {
// socket for message
const socketNotification = {
// my object
}
console.log(socketNotification, 'socketNotifcication')
socket.broadcast.emit(`messageSocket${member.memberId}`, socketNotification)
})
await Promise.all(promises)
io.emit(action2.conversationId, messages) // "newMessage"
} catch (err) {
throw err
}
})
.map()
loop that you never use. – Insubstantialids
multiple times. – Luculentsocket.on
multiple times to catch different events. Is that something wrong with it? – Luculent_id
. So why when I emit usingSocket.emit(_id, message)
does not emit the event? And when I doio.emit
||socket.broadcast.emit
it emits multiple times. Question-> Socket emits onevent
orlistners
. Please reply to this. – Luculent