React error when closing WebSocket connection with server

I am new to react, currently i am working on react app with offline speech recognition. And it seems pretty challenging to me. For now I am just only trying to figure out how web sockets and connections work. Here is my code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useRef, useEffect } from 'react';
const URL = 'ws://localhost:2700';
const sampleRate = 16000;
const SpeechRecoPage = () => {
const socket = useRef(null);
// calls when page renders
useEffect(() => {
if (!socket.current) {
socket.current = new WebSocket(URL);
};
socket.current.onopen = function () {
console.log('Connection established');
socket.current.send(`{ "config" : { "sample_rate" : ${sampleRate} } }`);
};
socket.current.onmessage = function (event) {
console.log(`Received message: ${event.data}`);
};
socket.current.onclose = function (event) {
console.log(`Connection closed: ${event.code} ${event.reason}`);
};
socket.current.onerror = function (error) {
console.log(`Error: ${error.message}`);
};
// Clean up WebSocket connection on component unmount
return () => {
if (socket.current.readyState === WebSocket.OPEN) { // <-- This is important
socket.current.close();
}
};
}, [socket]);
const closeConnection = () => {
socket.current.close()
};
return (
<div>
<h1>some text</h1>
<button onClick={closeConnection}>Close server connection</button>
{/* {isRecording ? (
<button onClick={stopRecording}>Stop Recording</button>
) : (
<button onClick={startRecording}>Start Recording</button>
)} */}
</div>
);
};
export default SpeechRecoPage;
</code>
<code>import React, { useRef, useEffect } from 'react'; const URL = 'ws://localhost:2700'; const sampleRate = 16000; const SpeechRecoPage = () => { const socket = useRef(null); // calls when page renders useEffect(() => { if (!socket.current) { socket.current = new WebSocket(URL); }; socket.current.onopen = function () { console.log('Connection established'); socket.current.send(`{ "config" : { "sample_rate" : ${sampleRate} } }`); }; socket.current.onmessage = function (event) { console.log(`Received message: ${event.data}`); }; socket.current.onclose = function (event) { console.log(`Connection closed: ${event.code} ${event.reason}`); }; socket.current.onerror = function (error) { console.log(`Error: ${error.message}`); }; // Clean up WebSocket connection on component unmount return () => { if (socket.current.readyState === WebSocket.OPEN) { // <-- This is important socket.current.close(); } }; }, [socket]); const closeConnection = () => { socket.current.close() }; return ( <div> <h1>some text</h1> <button onClick={closeConnection}>Close server connection</button> {/* {isRecording ? ( <button onClick={stopRecording}>Stop Recording</button> ) : ( <button onClick={startRecording}>Start Recording</button> )} */} </div> ); }; export default SpeechRecoPage; </code>
import React, { useRef, useEffect } from 'react';

const URL = 'ws://localhost:2700';
const sampleRate = 16000;

const SpeechRecoPage = () => {
  const socket = useRef(null);

  // calls when page renders
  useEffect(() => {
    if (!socket.current) {
      socket.current = new WebSocket(URL);
    };

    socket.current.onopen = function () {
      console.log('Connection established');
      socket.current.send(`{ "config" : { "sample_rate" : ${sampleRate} } }`);
    };

    socket.current.onmessage = function (event) {
      console.log(`Received message: ${event.data}`);
    };

    socket.current.onclose = function (event) {
      console.log(`Connection closed: ${event.code} ${event.reason}`);
    };

    socket.current.onerror = function (error) {
      console.log(`Error: ${error.message}`);
    };

    // Clean up WebSocket connection on component unmount
    return () => {
        if (socket.current.readyState === WebSocket.OPEN) { // <-- This is important
            socket.current.close();
        }
    };
  }, [socket]);

  const closeConnection = () => {
    socket.current.close()
  };

  return (
    <div>
      <h1>some text</h1>
      <button onClick={closeConnection}>Close server connection</button>
      {/* {isRecording ? (
        <button onClick={stopRecording}>Stop Recording</button>
      ) : (
        <button onClick={startRecording}>Start Recording</button>
      )} */}
    </div>
  );
};

export default SpeechRecoPage;

Here is my logs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[Log] [HMR] Waiting for update signal from WDS... (0.chunk.js, line 56991)
[Log] Connection established (main.chunk.js, line 1328)
[Error] WebSocket connection to 'ws://localhost:2700/' failed: The operation couldn’t be completed. Socket is not connected
[Log] Error: undefined (main.chunk.js, line 1338)
[Log] Connection closed: 1006 (main.chunk.js, line 1335)
</code>
<code>[Log] [HMR] Waiting for update signal from WDS... (0.chunk.js, line 56991) [Log] Connection established (main.chunk.js, line 1328) [Error] WebSocket connection to 'ws://localhost:2700/' failed: The operation couldn’t be completed. Socket is not connected [Log] Error: undefined (main.chunk.js, line 1338) [Log] Connection closed: 1006 (main.chunk.js, line 1335) </code>
[Log] [HMR] Waiting for update signal from WDS... (0.chunk.js, line 56991)
[Log] Connection established (main.chunk.js, line 1328)
[Error] WebSocket connection to 'ws://localhost:2700/' failed: The operation couldn’t be completed. Socket is not connected
[Log] Error: undefined (main.chunk.js, line 1338)
[Log] Connection closed: 1006  (main.chunk.js, line 1335)

The main thing that I do not understand: if connection is closed and I got this error, where I got this error and how to avoid it?

Appreciate

Tried nothing, just do not understand

New contributor

Фёдор Курушин is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật