Add WebSocket provider and handler for changePlugin
This commit is contained in:
parent
459d334732
commit
fcc81cf7e5
|
@ -1,12 +1,15 @@
|
|||
import React from "react";
|
||||
import { Grommet } from "grommet";
|
||||
import Core from "./Core";
|
||||
import WebSocketProvider from "./WebSocket";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<WebSocketProvider>
|
||||
<Grommet plain>
|
||||
<Core />
|
||||
</Grommet>
|
||||
</WebSocketProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -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}
|
||||
</>;
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
Loading…
Reference in New Issue