-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Instead, we'll try once to connectr the WebSocket on page load. See #52 for implementing automatic reconnection
- Loading branch information
Showing
5 changed files
with
61 additions
and
31 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
cueglow-webui/src/ConnectionProvider/ConnectionProvider.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { useEffect, useState } from "react" | ||
|
||
// TODO this module should provide automatic reconnection in the future | ||
// see https://github.com/cueglow/cueglow/issues/52 | ||
|
||
const webSocketPath = "ws://" + window.location.host + "/ws" | ||
const webSocketConnection = new WebSocket(webSocketPath) | ||
|
||
export enum ConnectionState { | ||
Connecting, | ||
Open, | ||
Closed, | ||
} | ||
|
||
function mapReadyStateToConnectionState(readyState: Number) { | ||
switch (readyState) { | ||
case 0: return ConnectionState.Connecting; | ||
case 1: return ConnectionState.Open; | ||
case 2: return ConnectionState.Closed; | ||
case 3: return ConnectionState.Closed; | ||
} | ||
} | ||
|
||
export function useConnection() { | ||
const [connectionState, setConnectionState] = | ||
useState(mapReadyStateToConnectionState(webSocketConnection.readyState)); | ||
|
||
// add event handlers to WebSocket once | ||
useEffect(() => { | ||
webSocketConnection.addEventListener( | ||
"open", () => {setConnectionState(ConnectionState.Open)} | ||
); | ||
webSocketConnection.addEventListener( | ||
"close", () => {setConnectionState(ConnectionState.Closed)} | ||
); | ||
}, []) | ||
|
||
return connectionState; | ||
} |