I have a problem and no clue about what is wrong. I use socket actions in two specific components App.js and MyComp.js. In App.js the socket is connected however when I'm going to MyComp.js the sockets disconnects and then connects again.
To understand better my problem on the client side I created a singleton Socket instance like this:
import io from 'socket.io-client';
const ENDPOINT='localhost:5001'
export const socket = io(ENDPOINT);
After that I imported this in my App.js, because from here I want to listen for global notifications and if I get some I will dispatch some actions with Redux. So my App.js
import {socket} from './Socket'
function App() {
useEffect(() => {
console.log('I am called')
socket.on('SERVER_RESPONSE', (msg) => {
console.log('this is my msg',msg)
})
}, [])
...some react routings
And the component where I use socket.io and always disconnects the socket when the component is loaded:
function MyComp(props) {
const sendMessage = () => {
socket.emit('HELLO_THERE');
}
return ( <Button variant="outlined" color="secondary" onClick={sendMessage}> Send msg</Button>)}
export default MyComp
On the server side I use a handlig file for my socket actions like this:
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE"]
}
});
io.on("connection", (socket) => {
console.log('A socket has connected', socket.id);
socket.on('event://send-message', (msg) => {
socket.emit("event://get-message", `Ezt kaptam valaszul ${msg}`)
})
socket.on('HELLO_THERE', () => {
socket.emit('SERVER_RESPONSE', 'Hello szia')
})
socket.on('disconnect', () => {
console.log('The user had left')
})
});
export default httpServer
And import in my index.js like this:
import httpServer from './socketconnection.js'
httpServer.listen(Number(PORT) + 1, () => {
console.log(`Socket listening on port ${Number(PORT) + 1}!`);
});
Result:
A socket has connected AHP-YDJuJgcsSSRoAAAD -> here i loaded the main App.js page
The user had left -> here is loaded MyComp
A socket has connected yX8_pcR7UdFeMGSSAAAF -> the MyComp has fully loaded
What am I doing wrong? Thanks in advance :)