I've researched this for almost 2 days now and can't seem to find an answer. I am trying to build an app where I use sockets to notify my front end that something has changed on the server. Note - I am not using any action on the front end (so this makes this question different from the one such as what's found on this thread for example: socket.io emits multiple times)
Unfortunately the socket.io on the server side fires the same event multiple times. From everything I have read I understand this is because the connection stays open and every-time the server restarts it fires a connection. There should be a way for me to prevent it from emiting a duplicate event, but I can't seem to figure it out.
Here is my server side code:
// main file
const express = require('express');
const app = express();
const routes = require('./routes/index');
const server = app.listen(process.env.PORT || 3001, () => {
console.log('listening on port 3001');
});
const io = require('socket.io')(server);
app.use('/sockets', socketFile(io))
module.exports = app;
// socketFile (same directory)
module.exports = function(io){
var express = require('express');
var router = express.Router();
var request_m = require('request')
router.post('/', function(req,res, next){
const custom_message = req.body.custom_message
io.sockets.emit('newMessage', {call: custom_message})
next();
})
return router
}
Her is the front end:
import React, {Component} from 'react';
import io from 'socket.io-client'
const socket = io('/');
class App extends Component {
constructor(){
super()
this.state={
}
}
componentDidMount(){
socket.on('newMessage', function (data) {
this.setState({newMessage: data.call})
}
}
render(){
return (
<div> </div>
);
}
}
export default App;
thank you All!
an additional note: in the socketFile I did also originally have
io.on('connection', function(socket){
...
})
but that seemed unnecessary since I don't need to listen for anything, and only emit when that router is hit by an external api. in any case the result was the same. To be clear, what happens is that when the route in socketFile is accessed and it now has a custom_message (let's call it 'hello world')...the server emits 'hello world' twice.