T
T
takoyklasnii2019-10-26 15:55:14
React
takoyklasnii, 2019-10-26 15:55:14

Why persistent connection to webSocket react?

There is a Panel.js component.
The code is written in it:

const socket = new WebSocket("ws://localhost:3001");
  const [messages, setMessages] = useState(["Test message"]);
  useEffect(() => {
    socket.onmessage = msg => {
      const incomingMessage = `Message from WebSocket: ${msg.data}`;
      setMessages(messages.concat([incomingMessage]));
    };
  });

  useEffect(() => () => socket.close(), [socket]);

  socket.onopen = () => {
    console.log("Connected");
  };

It has a Chat.js component, I pass socket to it
Inside Chat.js I have a button function:
function __handleSendMessage(e) {
    socket.send(123321);
  }

Why does every time I press the button I get a re-render and it says Connected in the console? That is, I clicked the button - Connected, clicked again (2) Connected ?
If I click faster than Connected - the error
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state takes off.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question