Socket.Io event hitting multiple times

308 Views Asked by At

index.js

 const messageContainer = document.querySelector('.msg');
const append = (message, position) => {
    console.log(message)
    const messageElement = document.createElement('div');
    messageElement.innerText = message;
    messageElement.classList.add('message');
    messageElement.classList.add(position);
    console.log(messageElement)
    messageContainer.append(messageElement);
    console.log(messageContainer)
};
const SERVER = "http://localhost:3010";
var socket = io(SERVER);
socket.on('receive_message', (message) => {
    console.log('Connected');
    console.log(message.content);
    setRMsg(message);
    console.log(rmsg)
    // append(`${message ? message.name : ''}: ${message ? message.content : ''}`, 'right');
    // // if (message.sendBy === 'user') {
        // append(`${message.content} `, 'left');
    // };
});
console.log(rmsg);
if (rmsg && rmsg != '') {
    append(`${rmsg.content} `, 'left');
    setRMsg('')
}
const send = () => {
    console.log('*95')
    console.log(sending)
    if (sending === '' || sending.senderChatID === '' || sending.content === '' || id === '') {
        console.log('***')
        toast.error('Missing Required Field', {
            position: "top-right",
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
        });
    }
    else {
        let obj = {
            senderChatID: sending.senderChatID,
            receiverChatID: id,
            content: sending.content,
            sendBy: sendVia,
            chatId: id,
            name: name ? name.name : '',
            profile_pic: name ? name.profile_pic : '',
            role: name ? name.role : '',
            createdAt: new Date(Date.now()),
            user_id: id
        };
        append(`${name ? name.name : ''}: ${sending.content}`, 'right');
        const input = document.getElementById('messageInp');
        input.value = '';
        socket.emit('send_message', obj);
}

'recieve_message' event is hitting multiple times but it must hit single time whereas on click of button send function works fine but while recieving message it gets hit multiple time don't know why as i am new to socket.io may be I was doing small mistake. Any help will be appreciated

1

There are 1 best solutions below

0
On BEST ANSWER

You're probably re-registering the socket.on(...) at each re-render of your React component. Get that code inside a useEffect with [] array to do that just one time like so :-

const socketObj = useRef(io("http://localhost:3010"));
const socket = socketObj.current;

useEffect(()=>{
socket.on('receive_message', (message) => {
    console.log('Connected');
    console.log(message.content);
    setRMsg(message);
    console.log(rmsg)
    // append(`${message ? message.name : ''}: ${message ? message.content : ''}`, 'right');
    // // if (message.sendBy === 'user') {
        // append(`${message.content} `, 'left');
    // };
});
},[]);

Here I have used socket as a ref since I believe it won't change once initialized and participate in the render flow but you can even make it as a state as well if you need.