Reputation: 21
Hello guys i have simple example with sockets:
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
var userCount = 0;
io.on('connection', function (socket) {
userCount++;
io.emit('userCount', { userCount: userCount });
socket.on('disconnect', function() {
userCount--;
io.emit('userCount', { userCount: userCount });
});
});
and frontend:
const [userCount, setuserCount] = useState(0);
socket.on('userCount', function (data) {
setuserCount(data.userCount);
});
I dont understand, but it fire so much requests .. And my question is this proper way to work with sockets?
Upvotes: 1
Views: 1871
Reputation: 50664
The issue seems to be with your frontend. The following code runs multiple times everytime your component renders:
socket.on('userCount', function (data) {
setuserCount(data.userCount);
});
This means that you're adding multiple event listener functions for the one userCount
event. To fix this, you can use React's useEffect()
hook, which you can use to run code once when your component mounts:
import React, {useState, useEffect} from "react";
...
// Inside your component:
const [userCount, setuserCount] = useState(0);
useEffect(() => {
const listener = data => setuserCount(data.userCount);
socket.on('userCount', listener);
return () => socket.off('userCount', listener);
}, [setuserCount]);
This way your listener will only be added once when your component mounts, and not multiple times. The cleanup function returned from the useEffect hook will also allow you to remove the listener when the component unmounts (thanks @Codebling for this suggestion). Your socket.on callback will still execute multiple times as socket.io will call it whenever your event occurs.
Upvotes: 2
Reputation: 380
I have found similar code here (http://sahatyalkabov.com/jsrecipes/#!/backend/who-is-online-with-socketio) and yes, this is the correct way to use sockets. It fires so many requests because every time a user connects and every time a user disconnects a message is fired (including when you reload. when you reload it fires twice, 1 for getting out and 1 for getting back on the site).
Upvotes: 0