Ad

SetInterval On Socket.io Function In ComponentDidMount/Update?

- 1 answer

I display the online users on my website that I'm building and this online user counter doesn't refresh itself automatically. So when I open this site in another tab, the counter increases in the new tab (I guess because it just renders), but in the old tab the counter doesn't update.

The online counter function with socket.io from the backend:

getOnline = () => {
        socket.on('onlineCount', (data) => {
            this.setState({ online: data });
        });
    };

And in my component:

    componentDidMount() {
        this.getOnline();
    }

    componentDidUpdate() {
        setInterval(() => this.getOnline(), 1000);
    }

I want the counter to update automatically without refreshing the page. In the terminal, it updates every 5 seconds so the backend works. And when I refresh the page it also updates. This site never has to be refreshes because it's a single page application so how can I achieve this function to run itself repeatedly and refresh the counter? I tried setInterval but no luck so far. Thanks!

Ad

Answer

ANSWER: with this in server.js, now automatically updates on client side. No need to refresh manually.

io.on('connection', (socket) => {
    console.log('Online: ' + socket.client.conn.server.clientsCount);

    interval = setInterval(() => emitOnline(socket), 5000);
    socket.on('disconnect', () => {
        console.log('Online: ' + socket.client.conn.server.clientsCount);
    });
});
const emitOnline = (socket) => {
    const response = socket.client.conn.server.clientsCount;
    socket.emit('onlineCount', response);
};
Ad
source: stackoverflow.com
Ad