Answer the question
In order to leave comments, you need to log in
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");
};
function __handleSendMessage(e) {
socket.send(123321);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question