javascriptreactjswebsocketemit

ReactJS Chat Websockets emits message twice


I have a Chat component which works fine on the happy flow but when I go on another view (meaning I exit the chat component) and come back after that in the chat component, I get duplicates messages.

I placed an console.log into the function which is triggered by the enter event but it displays only once. However, the emit from inside trigger twice I think because on the server side (nodeJs) I get the data twice.

This is my code:

function Chat() {     
    let [chatInput, setChatInput] = useState('');   
    let [chatArea, setChatArea] = useState([]);     

    const handleOnChange = (e) => {
        setChatInput(e.target.value) 
    }

    useEffect(() => {                      
        const addTextMessage = (event) => {
            if (event.keyCode === 13 && chatInput.value !== '') {                
                event.preventDefault(); 
                
                socket.emit('chat', {
                    message: chatInput.value
                });                
                                                      
                setChatInput('');              
            }  
        }

        const chatInput = document.querySelector('.chat-input input');
        chatInput.addEventListener("keyup", addTextMessage, false);

        socket.on('chat', (data) => {
            setChatArea(prevInputState => (                    
                [...prevInputState, <section key={prevInputState.length}>{data.sender}: {data.message}</section>]
            ))                                     
        })  

        return () => {            
            chatInput.removeEventListener("keyup", addTextMessage, false);                
            socket.off('chat');        
        };  

    }, []);

    return (
        <React.Fragment>                                        
            <section className="chat-room">
                <div className="chat-area">
                    {chatArea}   
                </div>
                <div className="chat-input">
                    <input value={chatInput} onChange={handleOnChange} type="text" />
                </div>
            </section>         
        </React.Fragment>
    );
}

Solution

  • I found the problem. Contrary to what I was thinking, the issue was coming from my server side.

    I have placed my nsSocket.on('chat', (data) => { by mistake inside another nsSocket.on(' and after I extracted it outside, the problems were fixed.