Reputation: 876
I followed this tutorial and can get the system to work, but I cannot figure out how to export the front-end socket from the index.jsx to other parts of the app. I can get the initializer to run in other functions just fine, but it issues a new socket every time it is ran which causes other issues. If I could make the socket variable in the /pages/index.tsx a global variable it would solve all my issues.
Here is my /pages/index.tsx
import { useEffect } from "react";
import io from "socket.io-client";
let socket: any; //how can I export this to other parts of my app?
const Home = () => {
useEffect(() => {
socketInitializer();
}, []);
const socketInitializer = async () => {
// We just call it because we don't need anything else out of it
await fetch("/api/socket");
socket = io();
console.log('index initialized socket.id: ', socket.id)
};
}
export default Home;
I can put the socket iniaitlizer into other parts of my app and it will work, but the sockets have different ids so if I assign a room to 1 user the room only works for that 1 socket which is erased on other
Upvotes: 0
Views: 980
Reputation: 49303
Although I never worked with socket in Next.js, I think socketInitializer
should be called in the _app.js file which is the top-level component. Because in your current design, if a user does not land on your home page, your websocket code will never run. Maybe someone send a link of a specific page of your app to the user and user clicked on that page and navigated through app and never visited home page, so that user will never use socket service.
you need to create a singleton socket object, and with the help of closure you can use it inside functions and can export those functions. i explained how to set up socket here: UseEffect hook with socket.io state is not persistent in socket handlers
Upvotes: 1