2020-12-21 10:46:05 +01:00
|
|
|
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) => {
|
2020-12-31 20:53:42 +01:00
|
|
|
dispatch(setData(payload.data || {}));
|
2020-12-21 10:46:05 +01:00
|
|
|
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;
|