OSD-Frontend/src/WebSocket.js

43 lines
935 B
JavaScript
Raw Normal View History

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(setData(payload.data || {}));
dispatch(setPlugin(payload.plugin));
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;