Reputation: 25
Okay so i have no prior knowledge about Socket IO so please bear with me if my question i really stupid ;-; Any help at all is appreciated.
Basically what I'm trying to do is have my React front end get a 'signal' from the server. So I have an socket.emit('task-data-changed') server side and an 'io.on('task-data-changed)' on the front end but this does not seem to do anything and i have no idea why.
Here's my server side code:
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.origins('*:*');
io.on('connection', socket => {
console.log('a user connected');
socket.on("task-data", () => {
console.log('got task-data signal on the backend');
socket.emit("task-data-changed", 'everyone');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
Here's my React code:
useEffect(()=> {
Socket.on("task-data-changed",() => {
console.log('task data was changed on the backend');
});
return () => Socket.off("task-data-changed");
},[]);
const submitNewTaskHandler = () => {
console.log('trying to emit task-data');
Socket.emit('task-data');
}
Things i know are working i guess:
the problem is after that the socket.emit('task-data-changed') on the server-side and the Socket.on('task-data-changed') don't seem to be working.
Thank you for reading so far, apologies if I've used the wrong terminology.
Upvotes: 1
Views: 2398
Reputation: 317
Your code to set the event listener on your front-end socket seems fine:
useEffect(()=> {
Socket.on("task-data-changed",() => {
console.log('task data was changed on the backend');
});
return () => Socket.off("task-data-changed");
},[]);
But, my question to you is, why is that code inside of useEffect()
? You should put it wherever your Socket is originally made. Or, you could put it on the line just before Socket.emit('task-data');
To give some explanation, Socket.on() is a listener. In your case, it listens for 'task-data-changed'. Once you tell it to start listening, it will keep listening forever. So, you should just set the listener up once by using Socket.on(), and you usually do this right when you initialize the Socket. Just do it once and it will stay listening and running your callback function.
Upvotes: 2