connection: use other method of connected/disconnected hook

master
Florens Douwes 5 years ago
parent f1d741053e
commit 9a564e9844
  1. 25
      frontend/src/lib/Connection.ts

@ -10,6 +10,8 @@ class Connection {
socket: SocketIOClient.Socket; socket: SocketIOClient.Socket;
isConnected = new Sub<boolean>();
config = new Sub<Config | null>(); config = new Sub<Config | null>();
room = new Sub<Room | null>(); room = new Sub<Room | null>();
timeline = new Sub<Timeline | null>(); timeline = new Sub<Timeline | null>();
@ -23,6 +25,8 @@ class Connection {
calls: { [id: number]: Call } = {}; calls: { [id: number]: Call } = {};
constructor() { constructor() {
this.isConnected.set(false);
this.socket = io(this.url, { this.socket = io(this.url, {
autoConnect: false, autoConnect: false,
transports: ['websocket'] transports: ['websocket']
@ -41,10 +45,12 @@ class Connection {
setupSocketListeners() { setupSocketListeners() {
this.socket.on('connect', () => { this.socket.on('connect', () => {
this.isConnected.set(true);
this.onConnect(); this.onConnect();
}) })
this.socket.on('disconnect', () => { this.socket.on('disconnect', () => {
this.isConnected.set(false);
this.onDisconnect(); this.onDisconnect();
}) })
@ -314,21 +320,6 @@ export function roomTime(): number {
return (connection.serverTime() - room.startTime) * room.speedFactor; return (connection.serverTime() - room.startTime) * room.speedFactor;
} }
export function useIsConnected() { export function useIsConnected(): boolean {
const [isConnected, setIsConnected] = useState(connection.socket.connected); return useSub(connection.isConnected);
useEffect(() => {
let connectListener = () => setIsConnected(true);
let disconnectListener = () => setIsConnected(false);
connection.socket.on('connect', connectListener);
connection.socket.on('disconnect', disconnectListener);
return () => {
connection.socket.off('connect', connectListener);
connection.socket.off('disconnect', disconnectListener);
}
}, [isConnected]);
return isConnected;
} }

Loading…
Cancel
Save