0

I want to run the connect function only once so that it initiates a stompjs client. But it is being called 4 times and I am getting the following message in the browser:

VM1867 bundle.js:41684 WebSocket connection to 'ws://localhost:3000/chat/251/ios42gwd/websocket' failed: WebSocket is closed before the connection is established.

It connects to the websocket after 4th time though.

If I understand it correctly useRef supposed to persist the value between re-renders but apparently it's not doing it since I get the clientInit.current=false four times.

What am I doing wrong?

function App() {
  const [userData, setUserData] = useState({
    userId: null,
    name: "",
    connected: false,
  });

  const [connected, setConnected] = useState(false);
  const [stompClient, setStompClient] = useState(null);

  const clientInit = useRef(false);

  //should be called only once? but called 4 times. getting clientInit.current= false 4 times 
 too 
  const connect = () => {         console.log("inside connect");
    console.log("====================================");
    console.log(clientInit.current);
    console.log("====================================");
    clientInit.current = true;

    const socket = new SockJS("/chat");
    const tempstompClient = Stomp.over(socket);
    tempstompClient.connect(
      { "client-id": userData.userId },
      () => {
        setConnected(true);
        setStompClient(tempstompClient);
      },
      (er) => {
        console.error(er);
      }
    );
  };

  const registerUser = (e) => {
    e.preventDefault();
    setUserData({ ...userData, connected: true });
  };

  const handleUser = (event) => {
    const { value } = event.target;
    const uuid = uuidv4();
    setUserData({ ...userData, name: value, userId: uuid });
  };
  useEffect(() => {
    console.log("====================================");
    console.log("calling connect:", clientInit.current);
    console.log("====================================");
    if(!clientInit)
      connect();

    return () => {
      console.log("Doing stuff inside cleaning up", stompClient);
      if (stompClient) {
        console.log("====================================");
        console.log("disconnecting", stompClient);
        console.log("====================================");
        stompClient.disconnect();
      }
    };
  }, []);

  return userData.connected ? (
    <Chatbox
      userData={userData}
      stompClient={stompClient}
      connected={connected}
    />
  ) : (
    <Register handleUser={handleUser} handleSubmit={registerUser} />
  );
}

export default App;
danronmoon
  • 3,814
  • 5
  • 34
  • 56

1 Answers1

0

The problem goes away when I try it with vite instead of react-scripts. I guess, for some reason react-scripts is mounting, unmounting the component multiple times unnecessarily