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?