react-use-websocket
react-use-websocket copied to clipboard
Websocket closes automatically without reconnect - check my own custom hook which reuses this lib
Hi folks,
I will provide my implementation of websocket using react-use-websocket lib, and here are questions?
- Should I subscribe in useEffect as it is, or I can move
subscribe()call intoonOpenlistener? - Does it automatically reconnect internally or I have to do something additional?
- Why sometimes it closes automatically without reconnect? Did I miss something or?
- How can I integrate "ping" feature here with inteval?
const useWebSocketData = () => {
const [data, setData] = useState([]);
const { lastMessage, readyState, sendJsonMessage } = useWebSocket(config.websocketUrl, {
onOpen: () => {
console.log('open');
},
shouldReconnect: () => true,
onClose: () => {
console.log('close');
},
reconnectAttempts: 10,
reconnectInterval: 5,
retryOnError: true,
});
const subscribe = useCallback(
() => sendJsonMessage({ id: 'someId', topic: 'someTopic', event: 'sub', params: { binary: false } }),
[sendJsonMessage]
);
useEffect(() => {
if (readyState === ReadyState.OPEN) {
subscribe();
}
}, [readyState]);
useEffect(() => {
if (lastMessage?.data) {
const parsedData = JSON.parse(lastMessage.data);
setData((prev) => prev.concat(parsedData));
}
}, [lastMessage, setData]);
return {
data,
readyState,
};
};