O
O
Olya Kopyeva2020-09-01 14:14:44
React
Olya Kopyeva, 2020-09-01 14:14:44

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.onmessagedo 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();
    }, []);
}

How can this be fixed? Do I need to use useRef here at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-09-01
@imkopyova

if (event.wasClean === false) webSocket.current = new WebSocket("ws://url");

you just created a new socket here but did nothing else with it. Accordingly, nothing happens to incoming messages.
you need to re-assign onmessage (and onclose, otherwise if the connection drops again, then nothing will happen)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question