Animesh Bhardwaj
Animesh Bhardwaj

Reputation: 729

Real time notification with socket.io, react.js and node.js

I'm developing a gaming application with react.js, node.js, express.js and sequelize.

The application is simple, one player challenge another player (Active players) and play a game after challenge is accepted.

I'm trying to create a notification system with socket.io, but the socket.emit() isn't working under the socket.on() at node.js. I don't know what's going on?

Here my code:

React

Sending this challenge request on challenge button click:

socket.emit('challenge request', { 
    player1_Name : localStorage.getItem('user-name'),
    player2 : response.data.data.player2_id,
    game : response.data.data.gameId,
    gameOption : response.data.data.gameOptionId,
    challengeStatus : response.data.data.challengeStatus
});     

and trying to receive this notification from the node.js:

  socket.on("challenge-notify", function(data) {
    console.log("challenge Notify", data);
    helper(data.player1_Name,data.player2,data.game,data.gameOption);
  });  

Node

Here socket.emit('challenge-notify') function is not working under the socket.on('challenge request') method:

    io.on('connection', function (socket) {
        socket.on('challenge request', function (challengeReq) {
          socket.emit('challenge-notify', { 
            player1_Name : challengeReq.player1_Name,
            player2 : challengeReq.player2,
            game : challengeReq.game,
            gameOption : challengeReq.gameOption,
            challengeStatus : challengeReq.challengeStatus
        });
    });
});

If I put socket.emit('challenge-notify') method outside my socket.on('challenge request') method then I'm getting the result at console when my react component load.

But I want this result whenever challenge button clicked. How can I achieve this?

Upvotes: 1

Views: 5968

Answers (1)

Animesh Bhardwaj
Animesh Bhardwaj

Reputation: 729

Yeah, Finally I found the solution..

I want to use socket.emit inside the socket.on to do this I used io.sockets.emit method and it works fine.

socket.on('challenge request', function (challengeReq) {
        io.sockets.emit('challenge-notify', { 
            player1_Name : challengeReq.player1_Name,
            player1: challengeReq.player1,
            player2 : challengeReq.player2,
            game : challengeReq.game,
            gameOption : challengeReq.gameOption,
            challengeStatus : challengeReq.challengeStatus

        });
    });

Upvotes: 2

Related Questions