Next.js Discord

Discord Forum

`WebSocket` Component dismounts as soon as it is mounted

Unanswered
Maheśvara posted this in #help-forum
Open in Discord
I have a websocket component like this:

  export default function Websocket() {
    // useEffect(fn, [])
    useOnMount(() => {
      socket.on("connect", async () => {
        console.log("Connected to signaling server");
      });
  
      socket.on("disconnect", () => {
        console.log("Disconnected from signaling server");
      });
  
      return () => {
        socket.off();
        socket.disconnect();
      };
    });
  
    return <></>;
  }


And have it placed in one of my layout files like this:

  export default async function layout({ children }: React.PropsWithChildren) {
    const session = await getServerAuthSession();
    const user = session?.user;
  
    if (!user) {
      redirect("/");
    }
  
    const allClasses = await getAllUserClasses(user);
  
    return (
      <>
        <Websocket />
        ...
          More code here, some Jotai and such
        ...
      </>
    )


Whenever I try to connect to my web socket, it immediately dismounts and subsequently disconnects.

If I remove the dismount function, it connects and works, however that's obviously not desired.

Is there something I should do different? How to go about fixing this?

0 Replies