Add WebSocket provider and handler for changePlugin

This commit is contained in:
Ceda EI 2020-12-21 15:16:05 +05:30
parent 459d334732
commit fcc81cf7e5
3 changed files with 49 additions and 8 deletions

View File

@ -1,12 +1,15 @@
import React from "react";
import { Grommet } from "grommet";
import Core from "./Core";
import WebSocketProvider from "./WebSocket";
function App() {
return (
<Grommet plain>
<Core />
</Grommet>
<WebSocketProvider>
<Grommet plain>
<Core />
</Grommet>
</WebSocketProvider>
);
}

View File

@ -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}
</>;
}

42
src/WebSocket.js Normal file
View File

@ -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 (
<WebSocketContext.Provider value={socket}>
{children}
</WebSocketContext.Provider>
);
}
WebSocketProvider.propTypes = {
children: PropTypes.node
};
export default WebSocketProvider;