#websockets issue

9 messages · Page 1 of 1 (latest)

quartz cloak
#
'use client';

import { createContext, useContext, useMemo, useEffect } from 'react';
import io from 'socket.io-client';

const WSStateContext = createContext(null);

export function WSProvider({ children }){

  const wsInstance = useMemo(() => {
    if (typeof window == 'undefined') return null;

    const socket =  io({
      path: '/api/socket',
      serveClient: false,
      reconnection: true,
      reconnectionAttempts: 3,
      reconnectionDelay: 900,
      reconnectionDelayMax: 3000,
      randomizationFactor: 0.3,
    });

    return socket;
  }, []);

  useEffect(() => {
    return () => {
      wsInstance?.close();
    };
  }, []);
    
  return <WSStateContext.Provider value={wsInstance}>{children}</WSStateContext.Provider>;
};

export function useWS(){
  const context = useContext(WSStateContext);

  return context;
};```

why does it run wsInstance?.close(); right when i load the page and how do i prevent it from connecting to the socket multiple times?
rugged gazelleBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

dry raft
quartz cloak
#

what should i do then?

dry raft
#

it will only run once in production

quartz cloak
#

ok

dry raft
#

other option will be disable strict mode but I wouldn't recommend it since it help preventing some weird bug

quartz cloak
#

👍