Search code examples
javascriptreactjswebsocketstompjs

StompJs starting two websocket connections


React application, @stomp/stompjs library

If I start React app, it opens 2 websocket connections. console log network log

If I build and deploy it to server, it opens only one connection. console log network log

chat.js

import React from 'react';
import { Client, Message } from '@stomp/stompjs';

function Chat(props) {

const client = new Client({
    brokerURL: 'ws://localhost:8088/api/chat',
    debug: function (str) {
        console.log(str);
    },
    reconnectDelay: 5000,
});

client.onConnect = function (frame) {
    client.subscribe("/chat", function (message) {
        console.log("MESSAGE: " + message)
    })
};

client.onStompError = function (frame) {
    console.log('Broker reported error: ' + frame.headers['message']);
    console.log('Additional details: ' + frame.body);
};
client.activate();

return (
    <p>chat</p>
);
}

export default Chat

package.json

{
"name": "react-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@stomp/stompjs": "^6.1.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.21.1",
    "dotenv": "^10.0.0",
    "http-proxy-middleware": "^2.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2",
    "websocket": "^1.0.34"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && mv build/* ../src/main/resources/static'",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I don't want to always build my app or receive double events. How can I fix that?


Solution

  • WebSocket is a "side effect" and React.useEffect fixed it

    https://stackoverflow.com/a/57809487