UNPKG

@talend/react-cmf-cqrs

Version:

@talend/react-cmf plugin for CQRS backend architecture

54 lines (53 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useWebSocket = void 0; var _react = require("react"); var _constants = require("./constants"); var _registry = require("./registry"); const useWebSocket = (messageFilterFunction = () => true, id = 'default') => { var _websocketRef$current2; const websocketRef = (0, _react.useRef)(); const [lastMessage, setLastMessage] = (0, _react.useState)(); const sendMessage = (0, _react.useCallback)(message => { var _websocketRef$current; if (((_websocketRef$current = websocketRef.current) === null || _websocketRef$current === void 0 ? void 0 : _websocketRef$current.readyState) === _constants.WEBSOCKET_READY_STATE.OPEN) { websocketRef.current.send(message); } }, []); const sendJsonMessage = (0, _react.useCallback)(message => { sendMessage(JSON.stringify(message)); }, [sendMessage]); const onMessage = messageEvent => { const data = JSON.parse(messageEvent.data); if (messageFilterFunction(data)) { setLastMessage({ message: messageEvent, jsonData: data }); } }; (0, _react.useEffect)(() => { const ws = (0, _registry.getWebSocketFromRegistry)(id); websocketRef.current = ws; if (ws) { ws.addEventListener('message', onMessage); } return () => { if (ws) { ws.removeEventListener('message', onMessage); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return { lastJsonMessage: lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.jsonData, lastMessage: lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.message, readyState: (_websocketRef$current2 = websocketRef.current) === null || _websocketRef$current2 === void 0 ? void 0 : _websocketRef$current2.readyState, sendMessage, sendJsonMessage }; }; exports.useWebSocket = useWebSocket; //# sourceMappingURL=useWebSocket.hook.js.map