From fcc81cf7e5822749563700501fe0dad7537239ce Mon Sep 17 00:00:00 2001 From: Ceda EI Date: Mon, 21 Dec 2020 15:16:05 +0530 Subject: [PATCH] Add WebSocket provider and handler for changePlugin --- src/App.js | 9 ++++++--- src/Core.js | 6 +----- src/WebSocket.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 src/WebSocket.js diff --git a/src/App.js b/src/App.js index 4f9c3ef..1d5f2a2 100644 --- a/src/App.js +++ b/src/App.js @@ -1,12 +1,15 @@ import React from "react"; import { Grommet } from "grommet"; import Core from "./Core"; +import WebSocketProvider from "./WebSocket"; function App() { return ( - - - + + + + + ); } diff --git a/src/Core.js b/src/Core.js index b0a5ba5..e957457 100644 --- a/src/Core.js +++ b/src/Core.js @@ -7,7 +7,6 @@ import * as plugins from "./plugins"; function Core() { const coreState = useSelector(selectCore); const dispatch = useDispatch(); - console.log(plugins.default); const plugin = plugins.default[coreState.plugin]; const props = { data: coreState.data, @@ -27,10 +26,7 @@ function Core() { } } - {plugin ? - React.cloneElement(plugin(), props) - :null - } + {plugin ? plugin(props) :null} ; } diff --git a/src/WebSocket.js b/src/WebSocket.js new file mode 100644 index 0000000..cc4550a --- /dev/null +++ b/src/WebSocket.js @@ -0,0 +1,42 @@ +import React, { createContext } from "react"; +import PropTypes from "prop-types"; +import io from "socket.io-client"; +import { WS_BASE } from "./config"; +import { useDispatch } from "react-redux"; +import { setData, setPlugin } from "./coreSlice"; + +const WebSocketContext = createContext(null); + +export { WebSocketContext }; + +function WebSocketProvider({ children }) { + let socket; + + const dispatch = useDispatch(); + if (!socket) { + socket = io.connect(WS_BASE); + + socket.on("switchPlugin", (payload) => { + dispatch(setPlugin(payload.plugin)); + dispatch(setData(payload.data)); + if (payload.time) { + setTimeout(() => { + dispatch(setData({})); + dispatch(setPlugin(false)); + }, payload.time); + } + }); + } + + return ( + + {children} + + ); +} + +WebSocketProvider.propTypes = { + children: PropTypes.node +}; + +export default WebSocketProvider;