React - socket.io on() does not seem to do anything

So I have this react component which connects to the express server on port 3000. The express server does work and logs "someone connected" and "user disconnected" when they load in the lobby component. However, the on() bit in the client-side does not seem to do anything. I never get the "connected to backend" message to log in client console. From what I can see, I don't get errors and it does connect to the correct namespace(from the express logs). Not sure why this is not working.

import React, { useEffect } from 'react';
import io from 'socket.io-client';
import "./LobbyComponent.css";

function Lobby() {   

    useEffect(() => {
        handleSocket();
    }, []);

    const handleSocket = () => {
        const lobby = io('http://localhost:3000/lobby');
        lobby.on('connection', function (socket){
            console.log('connected to backend');

            socket.on('disconnect', function(){
                console.log('disconnected: ', socket);
            });   

        });  
        lobby.on('chat message', function(msg){
            console.log('message: ', msg);
        });

    };   

    return (
        <div>

        </div>
    )

}

export default Lobby;

server.js file

let express = require("express");
let app = express();
let server = require('http').Server(app);

server.listen(PORT, () => {
    console.log("Listening at:", PORT);
});


let io = require("socket.io").listen(server);

const chatNameSpace = io.of('/lobby');

chatNameSpace.on('connection', function(socket){
    socket.emit('chat message', 'everyone');

    console.log('someone connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

Upvotes: 3

Views: 5479

Answers (2)

This was a stupid mistake. It annoys me a bit that the client and server side uses two different names for the event. I'll leave this if anyone else is as blind as me.

It should be:

lobby.on('connect', function (){
    console.log('connected: ');
});

not:

lobby.on('connection', function (){
    console.log('connected: ');
});

Upvotes: 5

Adolfo Onrubia
Adolfo Onrubia

Reputation: 1831

You have to connect from front to back when initializing:

const socket = io.connect(process.env.REACT_APP_SOCKET_HOST, {
  forceNew: true,
});

Upvotes: 1

Related Questions