I am new to React.js and Socket.io. After learning a few basics of React, I wanted to build a simple real-time communication app.
I followed this YouTube video tutorial (https://www.youtube.com/watch?v=jD7FnbI76Hg&t=1339s) by Traversy Media on how to implement Socket.io for real-time chat application using Node and Vanilla JavaScript. I wanted to adopt a similar implementation for Node and React.js but I am experiencing weird behavior.
The problem is that my io.emit(...) is firing multiple times. In some cases, twice while in other cases, four times as you can see in the image below.
Server.js:
import { Server, Socket } from 'socket.io';
import * as http from 'http';
import express from 'express';
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
path: '/api',
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
io.on('connection', (socket: Socket) => {
//Welcome user
socket.emit('Welcome', 'This is a welcome message');
//Disconnect
socket.on('disconnect', () => {
io.emit('message', 'A user has left');
});
});
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`Server listening on port: ${port}`));
Client.tsx:
import React, { useEffect, useRef } from 'react';
import { initSocket } from './utils/Socket';
import { Socket } from 'socket.io-client';
const SocketComponent = () => {
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
const init = async () => {
socketRef.current = await initSocket();
socketRef.current?.on('message', (arg) => {
console.log(arg); //message logs 4 times
});
socketRef.current?.on('Welcome', (arg) => {
console.log(arg); //logs 2 times
});
};
init();
return () => {
if (socketRef.current) {
socketRef.current.off('connect');
socketRef.current.off('disconnect');
socketRef.current.disconnect();
}
};
}, []);
return <h1>Hello World</h1>;
};
export default SocketComponent;
initSocket.ts
import { io } from 'socket.io-client';
import { ServerConstants } from './Constants';
export const initSocket = async () => {
//ServerConstants.HOST => http://localhost:5000
return io(ServerConstants.HOST, {
forceNew: true,
reconnectionAttempts: Infinity,
timeout: 10000,
transports: ['websocket', 'polling'],
path: '/api',
});
};
Both server and client socket.io is version 4.5.1. I noticed in the YT video Brad uses 4.4.1. I have downgraded to 4.4.1 but it still emits multiple messages.
Please, how can I fix this issue?
Thank you in advance.