Nikola Stojaković
Nikola Stojaković

Reputation: 2305

Client data is not updated by Socket.io

I have online counter in navigation bar which is connected with online event. It shows number of online users right, but when I connect in another window, counter is not updated (nor when I close the window). It shows right number after refresh too.

Server

let currentConnections = {};
let numberOfConnections = () => Object.keys(currentConnections).length;

io.sockets.on('connection', (socket) => {
    console.log('New user connected.');
    currentConnections[socket.id] = { socket: socket };
    socket.emit('online', { count: numberOfConnections() });

    socket.on('disconnect', () => {
        console.log('User has disconnected.');
        delete currentConnections[socket.id];
        socket.emit('online', { count: numberOfConnections() });
    });
});

Client

var socket = io.connect('http://localhost:3000');

socket.on('online', function(data) {
    $("#online").html(data.count);
    console.log(data);
});

Upvotes: 1

Views: 1065

Answers (1)

jfriend00
jfriend00

Reputation: 707366

You need to broadcast the updated count to all connections, not to just the newly connected or disconnected connection. In both places you have it change this:

socket.emit('online', { count: numberOfConnections() });

to this:

// send new count to all connections
io.emit('online', { count: numberOfConnections() });   

Upvotes: 2

Related Questions