Socketio not correctly working with Nodejs/Typescript and React

Viewed 150

I have been trying to make socket.io work with my Nodejs and Typescript backend and React + JSX frontend, this is my first experience with socket.io but it has been a nightmare. This is the server.ts file

import Express, {Application} from 'express';
import dotenv from 'dotenv';

const app: Application = Express();
import http from 'http';
//getting the Socket Type from socket io
import {Socket} from 'socket.io';
//importing the IO object form seperate file
import {init, socket} from './utils/socketio'; // <--- seperate socketio.ts file

import teacher_route from './Routes/teacher';
import student_route from './Routes/student';
import cookie_check_route from './Routes/cookieCheck';
import bodyParser from "body-parser";
import cors from 'cors';
import cookieParser from "cookie-parser";

const server = http.createServer(app);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
dotenv.config();
app.use(cors({
    origin: "http://localhost:3000",
    credentials: true,
}));

//initializing the io
init(server);


app.use(cookieParser());

app.use('/t', teacher_route);
app.use('/s', student_route);
app.use('/c', cookie_check_route);

//connecting the io
socket().on("connection", (socket: Socket)=> {
    console.log("reached server")
    socket.on("joined", (data: object)=> {
        console.log("reached joined")
        //@ts-ignore
        socket.emit("joined2", {
            //@ts-ignore
            full_name: "student[0].full_name",
            attendance: "",
            average_score: "",
            average_attendance: ""
        })
    })
})


server.listen(process.env.PORT);

SocketIO.ts file on the backend

import socketIo, {Socket} from 'socket.io';
let io: any;


//@ts-ignore
const init = (httpServer)=>{
    //@ts-ignore
    io = socketIo(httpServer, {
        cors: true,
        origins: ["http://127.0.0.1:3000"]
    });
    return io;
}

const getIO = () => {
    if(!io){
        throw new Error("Socket.io is not initialised!");
    }
    return io;
}

const socket = () => {
    return getIO().on("connection", (socket: Socket)=> {
        // console.log("inside socketio.ts file")
        return socket;
    })
}

export {init, getIO, socket};

This is the useEffect hook in StudentPortal.jsx file

useEffect(()=> {
        setLoader(true)
        socket.emit("joined"); // <--- emmiting an event
        axios.get(`${config.apiEndpoint}/s/checkclasses`, {
            withCredentials: true
        }).then(response => {
            setClasses(true);
            setDisableSubmit(false);
            setLoader(false)
            if(response.data.class_data_array){
                setClassData(response.data.class_data_array.reverse());
            }
        });
    }, [addedClass])

And Finally this is the Class.jsx file where i want to finally get that event

    socket.on("joined2", (data)=> {
        // setClassData([...classData, data]);
        console.log("Class.jsx socket");
    })

So the gist of this is that i am emmitting an event from StudentPortal.jsx named joined and listening for it in the Server.ts and in it's body, i am emmitting another event named Joined2 and listening for it in the Class.jsx, i have tried many many different things, placed socket connection in different files, tried to connect first and then emmit, and so much more, nothing seems to work. Any help is truly appreciated. Thank you

0 Answers
Related