Open ebasic opened 1 year ago
Hi folks,
I will provide my implementation of websocket using react-use-websocket lib, and here are questions?
react-use-websocket
subscribe()
onOpen
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, }; };
Hi folks,
I will provide my implementation of websocket using
react-use-websocket
lib, and here are questions?subscribe()
call intoonOpen
listener?How can I integrate "ping" feature here with inteval?