Ad

Listening Socket.io Event Works Server's Side But Not Client's Side

I am working on a student project, a dating website. I recently tried to use Socket.io but I encounter a problem

I would like to emit an event when a user views a profile

Server side listening: Update database

Client side listening: display a notification

When I emit the event 'view user', I can listen to it on the server side, it works

But when I try to listen to on the client side, it does not work

Emit the event :

socket.emit('view user', userId, userTarget)

Listening to it on the server side :

export const listenView = (socket) => {
  socket.on('view user', (userId, userTarget) => {
    console.log(`${ userId } viewed ${ userTarget }`)
    //viewUser(userId, userTarget)
  })
}

Listening on the client side :

componentDidMount () {
  console.log('MOUNTED')
  socket.on('view user', (userId, userTarget) => {
    console.log(`test viewed listening ${ userId } views ${ userTarget }`)
  })
}

It works on the server side : 724688ca-a9a5-4863-ace8-99e541c63b8f viewed 53bdd4e0-10db-43dd-b57b-6efead866517

But on the client side only MOUNTED is printed instead of

MOUNTED
test view listening 724688ca-a9a5-4863-ace8-99e541c63b8f viewed 53bdd4e0-10db-43dd-b57b-6efead866517

Am I doing something wrong ?

Thank you in advance !

EDIT: Socket is always the same, I checked the ID on the client side and on the server side and it's the same

Ad

Answer

I found the problem. To see the events on the client side I had to emit it from the server :

export const listenView = (socket) => {
  socket.on('view user', (userId, userTarget) => {
    console.log(`${ userId } viewed ${ userTarget }`)
    socket.emit('view user', userId, userTarget)
    //viewUser(userId, userTarget)
  })
}
Ad
source: stackoverflow.com
Ad