Socket.io only emits to rooms after recompile of react client code

`I am trying to implement socket.io messaging into my react application, and I’m stuck on getting the sockets to work consistently. The socket only works after recompiling the react app, as in, when I first start up the app and api server, the socket connects but messaging doesn’t work, but after a recompile it works fully as intended. I’m relatively new to react and sockets, so I’m not entirely sure where to look.

I imagine it has something to do either with the api server:

const Koa = require('koa');
const app = new Koa();
const http = require('http');
const { Server } = require('socket.io');
const cors = require('@koa/cors');

app.use(cors({ origin: '*' }));
const server = http.createServer(app.callback());

//instatiate new Server
const io = new Server(server, {
    autoConnect: false,
    cors: {
        origin :"http://localhost:3000", 
        methods: ["GET", "POST"], 
        autoConnect: false,
    },

});

io.on('connection', (socket) => {
    console.log('Socket.IO client connected');

    socket.on("join_room", (data)=>{
        console.log("room joined: ", data);
        socket.join(data);
    })

    socket.on('message_sent', (data) => {
        console.log('Received:', data.message, " in ", data.room);
        //socket.broadcast.emit('received_message', data.message); //this is only for sending a message for everyone
        socket.to(data.room).emit('received_message', data.message);
    });

});

require('./config/draught_services_routes.js')(app);

server.listen(3001, () => {
    console.log('Server is running on port 3001');
});

or the Messages.js react component:

import { Box, TextField, Typography, Button } from '@mui/material';
import { Fragment, useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3001');


//just checking if the thing connects right
socket.on('connect', () => {
    console.log('Connected to server successfully!');
});
socket.on('connect_error', (error) => {
    console.error('Connection error:', error);
});


export default function Inbox({userID}) {
    const [message, setMessage] = useState('');
    const [room, setRoom] = useState('');
    const [messages, setMessages] = useState([]);
    const [roomName, setRoomName] = useState("");


    const handleSendMessage = () => {
        if (message.trim() === '') return;
        // Sort the usernames alphabetically
        const sortedUsernames = [userID.username, room].sort();
        setRoomName(sortedUsernames.join(''));

        console.log("SENDING MESSAGE ", message, " to room ", roomName);
        socket.emit('message_sent', { message: userID.username + ": " + message, room: roomName });
        setMessages((prevMessages) => [...prevMessages, userID.username + ": " + message]);
        setMessage('');
    };


    const handleJoinRoom = () => {
        if (room.trim() === '') return;
        // Sort the usernames alphabetically
        const sortedUsernames = [userID.username, room].sort();
        setRoomName(sortedUsernames.join(''));

        console.log("JOINING ROOM ", sortedUsernames.join(''));
        socket.emit('join_room',sortedUsernames.join(''));
    };



    useEffect(() => {
        console.log('Message received' ); 
        socket.on('received_message', (message) => {
            setMessages((prevMessages) => [...prevMessages, message]);
        });

        return () => {
            socket.disconnect();
        };
    }, []);


    return (
        <Fragment>
            <Box
                sx={{
                    display: 'flex',
                    justifyContent: 'space-between', // Adjust spacing between the two sections
                    border: 0,
                    width: '100%', // Ensure the container spans the full width
                }}
            >
                <Box
                    sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: '45%', // Adjust width to your preference
                    }}
                >
                    <TextField
                        label="to: "
                        value={room}
                        onChange={(e) => setRoom(e.target.value)}
                        variant="outlined"
                        style={{ marginBottom: '5px', width: '100%' }}
                    />
                    <Button variant="contained" onClick={handleJoinRoom}>
                        confirm
                    </Button>

                    <TextField
                        label="Type a message..."
                        value={message}
                        onChange={(e) => setMessage(e.target.value)}
                        variant="outlined"
                        style={{ marginBottom: '10px', width: '100%' }}
                    />
                    <Button variant="contained" onClick={handleSendMessage} style={{ marginLeft: '10px' }}>
                        Send
                    </Button>
                </Box>

                <Box
                    sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: '45%',
                    }}
                >

                    <Typography variant="h6"> messages </Typography>
                    <div style={{ marginBottom: '5px', maxHeight: '200px', overflowY: 'scroll', width: '100%' }}>
                        {messages.map((msg, index) => (
                            <Typography key={index} variant="body1" style={{ textAlign: 'left' }}>
                                {msg}
                            </Typography>
                        ))}
                    </div>
                </Box>
            </Box>
        </Fragment>
    );
}

I’ve tried to move things around and add a delay to send_message to see if it has something to do with that, but to no avail. I’m not really sure what else I could do. Any general advice is appreciated! `

New contributor

Benito Sanchez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật