Answer the question
In order to leave comments, you need to log in
How to implement WebSocket connection recovery in React application?
The goal is to re-establish a WebSocket connection if the connection is closed inadvertently.
I tried to do this, but the problem is that after reopening the connection, messages come in but webSocket.current.onmessage
do not work.
export const useWebSocket = () => {
const webSocket = useRef();
useEffect(() => {
webSocket.current = new WebSocket("ws://url");
webSocket.current.onclose = event => {
if (event.wasClean === false) webSocket.current = new WebSocket("ws://url");
}
webSocket.current.onmessage = event => {
const { msg_type, data } = JSON.parse(event.data);
switch (msg_type) {
case "one_msg_type":
callOneFunction();
break;
case "another_msg_type":
callAnotherFunction();
break;
}
};
return () => webSocket.current.close();
}, []);
}
Answer the question
In order to leave comments, you need to log in
if (event.wasClean === false) webSocket.current = new WebSocket("ws://url");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question