I recently completed a tutorial on setting up a socket chat app, which I found at the following link: tutorial link. While I have successfully managed to get the system up and running, I'm facing an issue with exporting the front-end socket from the index.jsx to other parts of my application. Every time I run the initializer in other functions, it creates a new socket instance, leading to complications. If there was a way to make the socket variable in /pages/index.tsx a global variable, it would resolve all my current issues.
Let me share a snippet of my /pages/index.tsx code for reference:
import { useEffect } from "react";
import io from "socket.io-client";
let socket: any; //I need help exporting this to different parts of my app
const Home = () => {
useEffect(() => {
socketInitializer();
}, []);
const socketInitializer = async () => {
// Initiating socket connection
await fetch("/api/socket");
socket = io();
console.log('index initialized socket.id: ', socket.id)
};
}
export default Home;
While inserting the socket initializer into various sections of my application seems to work, each socket instance has a unique ID. Consequently, assigning a room to one user is exclusive to that particular socket, making it inaccessible to others.