2019-06-29 23:14:32 +00:00
|
|
|
import React, { useEffect } from 'react';
|
2019-06-29 23:57:11 +00:00
|
|
|
import { Websocket } from '@/plugins/Websocket';
|
2019-07-10 04:25:57 +00:00
|
|
|
import { ServerContext } from '@/state/server';
|
2019-06-29 23:14:32 +00:00
|
|
|
|
|
|
|
export default () => {
|
2019-07-10 04:25:57 +00:00
|
|
|
const server = ServerContext.useStoreState(state => state.server.data);
|
|
|
|
const instance = ServerContext.useStoreState(state => state.socket.instance);
|
|
|
|
const setServerStatus = ServerContext.useStoreActions(actions => actions.status.setServerStatus);
|
|
|
|
const { setInstance, setConnectionState } = ServerContext.useStoreActions(actions => actions.socket);
|
2019-06-29 23:14:32 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
// If there is already an instance or there is no server, just exit out of this process
|
|
|
|
// since we don't need to make a new connection.
|
|
|
|
if (instance || !server) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-09-09 00:48:37 +00:00
|
|
|
const socket = new Websocket(server.uuid);
|
2019-06-29 23:57:11 +00:00
|
|
|
|
|
|
|
socket.on('SOCKET_OPEN', () => setConnectionState(true));
|
|
|
|
socket.on('SOCKET_CLOSE', () => setConnectionState(false));
|
|
|
|
socket.on('SOCKET_ERROR', () => setConnectionState(false));
|
|
|
|
socket.on('status', (status) => setServerStatus(status));
|
2019-06-29 23:14:32 +00:00
|
|
|
|
2019-09-09 00:48:37 +00:00
|
|
|
socket.connect()
|
|
|
|
.then(() => setInstance(socket))
|
|
|
|
.catch(error => console.error(error));
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
socket && socket.close();
|
|
|
|
instance && instance!.removeAllListeners();
|
|
|
|
};
|
2019-06-29 23:57:11 +00:00
|
|
|
}, [ server ]);
|
2019-06-29 23:14:32 +00:00
|
|
|
|
|
|
|
return null;
|
|
|
|
};
|